[英]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構造函數中出現問題或發生其他錯誤,從而改變通常的輸出? 如果是這樣,誰能給我一個例子?
include <stdexcept>
Base()
{
cout << "Base"<<endl;
throw std::runtime_error("error");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.