Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the destructor called when a delegating constructor throws?

It is well known that if a constructor throws, then all fully constructed sub-objects will be destroyed in reverse order including member data and all kinds of base classes. The destructor does not get called for non-delegating constructors though. For a delegating constructor the object has been constructed when the constructor body is entered, but construction continues somewhat. Therefore the question arises whether the destructor of the class is called, if the delegating constructor throws an exception from within its body?

class X
{
public:
    X();
    X(int) : X() { throw std::exception(); } // is ~X() implicitely called?
    ~X();
};
like image 446
Ralph Tandetzky Avatar asked Jul 15 '13 15:07

Ralph Tandetzky


People also ask

Is destructor called if constructor throws?

Destructors are only called for the completely constructed objects. When the constructor of an object throws an exception, the destructor for that object is not called.

Is destructor called when exception is thrown?

Yes, destructors are guaranteed to be called on stack unwinding, including unwinding due to exception being thrown. There are only few tricks with exceptions that you have to remember: Destructor of the class is not called if exception is thrown in its constructor.

Does destructor get called if constructor fails?

Constructor Failures by Herb Sutter Incidentally, this is why a destructor will never be called if the constructor didn't succeed -- there's nothing to destroy. "It cannot die, for it never lived." Note that this makes the phrase "an object whose constructor threw an exception" really an oxymoron.

How constructor and destructor are called?

Constructors are also called when local or temporary class objects are created, and destructors are called when local or temporary objects go out of scope. You can call member functions from constructors or destructors.


2 Answers

The rule is that the destructor is called for all fully constructed objects. The object is considered fully constructed once any constructor has finished, including the delegated constructor (even though the program continues in another constructor).

like image 161
James Kanze Avatar answered Oct 05 '22 22:10

James Kanze


The lifetime of an object begins when any constructor (i.e., in the case of delegation, the ultimate target constructor) is successfully completed. For the purposes of [C++03] §3.8, “the constructor call has completed” means any constructor call. This means that an exception thrown from the body of a delegating constructor will cause the destructor to be invoked automatically.

source.

And here is a nice article about delegating constructors, should anybody want to read it.

like image 43
Stefano Falasca Avatar answered Oct 06 '22 00:10

Stefano Falasca