问题
The output of the program below is:
begin try
Object() ctor
begin catch
Why is the Holder class's destructor not called? Is this a memory leak? Is it possible to call the Holder class's destructor without rethrowing?
#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;
}
回答1:
In this case, your Holder
object h
is not fully constructued, that is that h
's constructor had not finished its construction before the stack unwinding process had begun.
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.
来源:https://stackoverflow.com/questions/35858184/raii-failure-why-does-this-c-code-leak-throw-in-ctor-in-try-block-prevent