free memory when constructor throw exception
-
If constructor is throwing any execpetion after allocating some memory (using new) on heap then how can we free that allocated memory.
Ideally you avoid any activity that would throw an exception in the constructor. Instead of using new on the constructor. Mark the pointers as nullptr and then have a separate init function. But you might try
new (std::nothrow)
which will eat the exception and instead return nullptr. or you can do something like.
try {
ptr = new char[100];
} catch(std::bad_alloc& e) {
// Decide what to do.
}But overall, is a bad idea to throw on a constructor.
-
If constructor is throwing any execpetion after allocating some memory (using new) on heap then how can we free that allocated memory.
Move the memory allocation to a class of its own so that the new happens in its constructor and delete happens in its destructor. That should be the only responsibility of the allocating class. In the class whos constructor throws, create an object of the allocating class on the stack. Since destructors are only called for objects that are fully constructed, the allocating class destructor is always guaranteed to be called.
«_Superman_» _I love work. It gives me something to do between weekends.
_Microsoft MVP (Visual C++) (October 2009 - September 2013)
-
If constructor is throwing any execpetion after allocating some memory (using new) on heap then how can we free that allocated memory.
Decently well though out description of the problem and solutions: C++ Constructors and Memory Leaks - J@ArangoDB[^]