簡體   English   中英

引發導致析構函數被調用的異常導致程序崩潰

[英]Throwing an exception which causes a destructor to be called crashes the program

考慮一下這小段代碼,它實際上是較大代碼庫的一部分:

class A
{
public:
    A()
    {
        std::cout << "A" << std::endl;
    }

    ~A()
    {
        std::cout << "~A" << std::endl;
    }
};

void f()
{
    A a;
    throw;
}

void g()
{
    try
    {
        f();
    }
    catch(...)
    {
        std::cout << "Caught" << std::endl;
    }
}

對於我的特殊情況,輸出結果是

A
~A

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.

似乎終止了程序,而不是捕獲異常。 不過,如果我刪除的構造,除了被逮住。

如果不仔細分析代碼,是否有可能知道導致此類行為的原因?

沒有操作數的throw-expression ,如您的代碼所示:

  • 重新拋出當前處理的異常(同一對象,而不是其副本)
  • 或者,如果當前沒有處理的異常,則調用std::terminate

我假設在處理異常時調用f() (我想您是直接從main或其他對象調用它)。 因此,將調用std::terminate

對象a不相關。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM