簡體   English   中英

在C ++中,如果基類的構造函數異常,那么構造函數和析構函數的順序可能是這樣?

[英]In C++,if the Base class constructor exception,then the sequence of constructor and destructor could be this?

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

class Base
{
public:
    Base()
    {
        cout << "Base"<<endl;
    }
    ~Base()
    {
        cout << "~Base"<<endl;
    }

};

class Child: public Base
{
public:
    Child()
    {
        cout << "Child"<<endl;
    }
    ~Child()
    {
        cout << "~Child"<<endl;
    }
};

int main()
{
    try
    {
        Child cc;
    }
    catch(...)
    {
    }

    return 0;
}

一般輸出將是

Base 
Child
~Child
~Base

但是,如果在Base是構造函數時遇到了可怕或異常的情況,則后繼可能是:

Base 
~Base
Child
~Child

誰能寫一個演示來說明這一點? C ++通常不會在構造函數中引發異常,但是如果引發異常,那么它會導致該輸出嗎?

感謝大家的幫助。 我不確定在通常的代碼中是否會發生這種情況。 是否可能在復雜的Base構造函數中出現問題或發生其他錯誤,從而改變通常的輸出? 如果是這樣,誰能給我一個例子?

如果Base類構造函數中發生異常,則不會調用任何析構函數。
僅僅是因為沒有需要銷毀的完整對象!

忍不住引用了Herb

“它不會死,因為它永遠不會生存!”

include <stdexcept>
Base()
{
    cout << "Base"<<endl;
    throw std::runtime_error("error");
}

暫無
暫無

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

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