下面程序的输出是:
begin try
Object() ctor
begin catch
为什么Holder类的析构函数没有被调用?这是内存泄漏吗?是否可以调用 Holder 类的析构函数而不重新抛出?
#include <iostream>
#include <exception>
class Object
{
public:
Object() { std::cout << "Object() ctor" << std::endl; }
~Object() { std::cout << "~Object() dtor" << std::endl; }
};
class Holder
{
public:
Holder() :myObjectP( new Object() )
{
throw std::exception();
}
~Holder()
{
std::cout << "~Holder()" << std::endl;
delete myObjectP;
}
private:
Object* myObjectP;
};
int main(int argc, char* argv[])
{
try
{
std::cout << "begin try" << std::endl;
Holder h;
}
catch ( ... )
{
std::cout << "begin catch" << std::endl;
}
return 0;
}
最佳答案
在这种情况下,你的Holder
对象h
还没有完全构造完成,也就是说h
的构造函数之前还没有完成它的构造堆栈展开过程已经开始。
C++11 15.2 Constructors and destructors (2)
An object of any storage duration whose initialization or destruction is terminated by an exception will have destructors executed for all of its fully constructed subobjects (excluding the variant members of a union-like class), that is, for subobjects for which the principal constructor (12.6.2) has completed execution and the destructor has not yet begun execution.
关于c++ - RAII 失败 - 为什么此 C++ 代码会泄漏? - 在 try block 中放入 ctor 可以防止 dtor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35858184/