Sign in to follow this  
lol

quick question about c++ exceptions in constructors

Recommended Posts

if a constructor throws an exception, is the object that was being constructed automatically deleted, or do I have to do that myself?

Share this post


Link to post
Share on other sites
Short answer: the destructor of the object being constructed is not called, the destructors of any already constructed base classes and members are called (in the reverse order of their construction), and finally the memory allocated for the object is deallocated (as a no-op if it's stack memory, using the operator delete corresponding to the operator new used for the allocation otherwise, which for placement new results, again, in a no-op).

Share this post


Link to post
Share on other sites
The object never existed, so it can't have its destructor called (nor does it need to). Any data members/bases that already got constructed (if the exception happens in the body of the constructor, that's all of them), then they exist, and they'll be automatically destructed - you don't have to do that yourself, for the same reason you don't have to do it yourself when an object goes out of scope.

The only time you have to call a destructor explicitly (as in 'MyClass::~MyClass()') is when you called its constructor explicitly (as in 'new (memory_location) MyClass()'). Which is basically never. (And when you don't have to, it is in fact wrong to try.)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this