quick question about c++ exceptions in constructors

Started by
2 comments, last by Zahlman 16 years, 8 months ago
if a constructor throws an exception, is the object that was being constructed automatically deleted, or do I have to do that myself?
Placeholder for better sig.
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.
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).
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.)

This topic is closed to new replies.

Advertisement