讓我們假設以下簡單的例子:堆棧展開如何處理析構函數調用?
#include <iostream>
struct foo {
~foo() {
std::cout << "~foo()" << std::endl;
}
};
struct bar {
foo x;
bar() : x() {
throw -1;
}
~bar() {
std::cout << "~bar()" << std::endl;
}
};
struct baz {
~baz() {
std::cout << "~baz()" << std::endl;
}
};
int main() {
try {
baz y;
bar z;
} // Destructor is called for everything fully constructed up to here?
catch(...) {
}
}
輸出是
~foo()
~baz()
所以很明顯bar
的析構函數沒有被調用。
這意味着什麼樣的資源分配將被髮布在bar
的析構函數中?
E.g.
struct bar {
CostlyResource cr;
bar() {
cr.Open(); // Aquire resource
// something else throws ...
throw -1;
}
~bar() {
if(cr.IsOpen()) {
cr.Release(); // Free resource
}
}
};
對於異常安全的實施緣故我能做些什麼,以確保bar
的資源成員正常釋放?
感謝您的額外輸入。我自己回答了這個問題,因爲我最近幾次看過這個話題。對於規範我嘗試了一次,我知道:-P ... – user0042
@ user0042你在回答中提出的解決方案將會是我的首選解決方案清單。另一個選擇是具有定製刪除器的'unique_ptr'。 –
至少我提到了智能指針,我很清楚你的擔憂。 – user0042