[英]c++ destructor throw exception by single object
我試圖理解為什么從析構函數中拋出異常會導致程序崩潰。 因為我發現了兩個拋出多個異常的對象的例子,編譯器無法處理多個異常,但在我的情況下,我只從析構函數拋出一個異常。 為什么我的程序仍然崩潰?
class MyClass {
private:
string name;
public:
MyClass (string s) :name(s) {
cout << "constructor " << name << endl;
}
~MyClass() {
cout << "Destroying " << name << endl;
throw "invalid";
}
};
int main( )
{
try {
MyClass mainObj("M");
}
catch (const char *e) {
cout << "exception: " << e << endl;
cout << "Mission impossible!\n";
}
catch (...) {
cout << "exception: " << endl;
}
return 0;
}
MingW g ++編譯器的解釋:
[P:\temp] > g++ foo.cpp foo.cpp: In destructor 'MyClass::~MyClass()': foo.cpp:14:15: warning: throw will always call terminate() [-Wterminate] throw "invalid"; ^~~~~~~~~ foo.cpp:14:15: note: in C++11 destructors default to noexcept
真的讓它扔掉你可以做到這一點:
~MyClass() noexcept(false){
由於C ++ 11析構函數被隱式聲明為noexcept
文檔
非拋出函數是所有其他函數(具有noexcept說明符的函數,其表達式的計算結果為true,以及析構函數 ,默認的特殊成員函數和釋放函數)
重點是我的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.