I was debating with some colleagues about what happens when you throw an exception in a dynamically allocated class. I know that malloc
gets called, and then the constructor of the class. The constructor never returns, so what happens to the malloc
?
Consider the following example:
class B
{
public:
B()
{
cout << "B::B()" << endl;
throw "B::exception";
}
~B()
{
cout << "B::~B()" << endl;
}
};
void main()
{
B *o = 0;
try
{
o = new B;
}
catch(const char *)
{
cout << "ouch!" << endl;
}
}
What happens to the malloced memory o
, does it leak? Does the CRT catch the exception of the constructor and deallocate the memory?
Cheers!
Rich
This exception can be thrown by any property assignment or method call that requires a memory allocation. For more information on the cause of the OutOfMemoryException exception, see the blog post "Out of Memory" Does Not Refer to Physical Memory. This type of OutOfMemoryException exception represents a catastrophic failure.
The exception that is thrown when there is not enough memory to continue the execution of a program. System. Insufficient Memory Exception OutOfMemoryException uses the HRESULT COR_E_OUTOFMEMORY, which has the value 0x8007000E.
OutOfMemoryException uses the HRESULT COR_E_OUTOFMEMORY, which has the value 0x8007000E. For a list of initial property values for an instance of OutOfMemoryException, see the OutOfMemoryException constructors. The value of the inherited Data property is always null.
The following example illustrates the OutOfMemoryException exception thrown by a call to the StringBuilder.Insert (Int32, String, Int32) method when the example tries to insert a string that would cause the object's Length property to exceed its maximum capacity.
A call to
new B();
resolves in two things:
new (xxx) B()
)If the constructor throw, the corresponding operator delete is called. The case where the corresponding delete is a placement one is the only case where a placement delete operator is called without the syntax ::operator delete(). delete x;
or delete[] x;
don't call the placement delete operators and there is no similar syntax to placement new to call them.
Note that while the destructor of B will not be called, already constructed subobjects (members or B and base classes of B) will be destructed before the call to operator delete. The constructor which isn't called is the one for B.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With