• Advertisement
Sign in to follow this  

quick question about c++ exceptions in constructors

This topic is 3845 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
Quote:
Original post by lol
if a constructor throws an exception, is the object that was being constructed automatically deleted, or do I have to do that myself?


A C++ Must read [smile].

That entire site is gold.

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
Sign in to follow this  

  • Advertisement