让我们假设以下简单的例子:堆栈展开如何处理析构函数调用?
#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