關於解構函式在stack-unwinding中扔出異常的程式碼分析

來源:互聯網
上載者:User

根據,MECPP 的條款11。開頭一段:

在有兩種情況下會調用解構函式。第一種是在正常情況下刪除一個對象,例如對象超出了範圍或被顯式地delete。第二種是異常傳遞的堆棧輾轉開解(stack-unwinding)過程中,由異常處理系統刪除一個對象。
    在上述兩種情況下,調用解構函式時異常可能處於啟用狀態也可能沒有處於啟用狀態。遺憾的是沒有辦法在解構函式內部區分出這兩種情況。因此在寫解構函式時你必須保守地假設有異常被啟用。因為如果在一個異常被啟用的同時,解構函式也拋出異常,並導致程式控制權轉移到解構函式外,C++將調用terminate函數。這個函數的作用正如其名字所表示的:它終止你程式的運行,而且是立即終止,甚至連局部對象都沒有被釋放。

幾乎讓人很費解,所以寫了下面這段code以協助理解:

#include <iostream>
#include <exception>
using namespace std;

class class_test {
    public:
        class_test(void){}
        ~class_test(void)
        {
            // throw bad_alloc();
            //如果此處扔出異常將會調用terminate()
            cout << "~class_test()....." << endl;
            cin.get();
         }
    private:
};
void funtest0(void)
{
    class_test obj;
    cout << "f0......" << endl;
    throw bad_alloc();
    cout << "funtest0()......" << endl;
}
void funtest1(void)
{
    class_test obj;
    cout << "f1....." << endl;
    funtest0();
    cout << "funtest1()......" << endl;
}      
     
int main()
try
{
    class_test obj;
    funtest1();
    cin.get();
    return 0;
}
catch(bad_alloc &e)
{
    cout << e.what() << endl;
    cin.get();
   
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.