【发布时间】:2016-08-12 00:13:47
【问题描述】:
如果我们用 g++ 或 clang 考虑下面的代码,至少在 main 函数中没有捕获到异常时,不会调用 Guard 类的析构函数。我做了一个谷歌搜索,没有找到任何有用的信息。
我在很多地方使用警卫类来实现 RAII。因此,我发现这非常令人失望,尤其是在处理信号量等资源时。
尽管 C++ 要求在抛出异常时调用析构函数。这是行为标准还是 libstdc++ 实现的原因?
感谢您在此问题上提供的任何帮助或建议。
#include<iostream>
#include<memory>
struct Guard
{
Guard()
: v(new int)
{
std::cout << "Guard()" << std::endl;
}
~Guard(){
std::cout << "~Guard()" << std::endl;
delete v;
}
private:
int *v;
};
void test(){
auto g = std::make_shared<Guard>();
throw("youch");
}
void test2(){
test();
}
int main(void){
// try{
test2();
// } catch(...){
// }
return 0;
}
附: : 我不希望在主函数中添加 try/catch 块,因为我很高兴能够将异常追溯到调试器中发出的位置。
【问题讨论】: