This is implementation of new operator in libstdc++:
_GLIBCXX_WEAK_DEFINITION void *
operator new (std::size_t sz) _GLIBCXX_THROW (std::bad_alloc)
{
void *p;
/* malloc (0) is unpredictable; avoid it. */
if (__builtin_expect (sz == 0, false))
sz = 1;
while ((p = malloc (sz)) == 0)
{
new_handler handler = std::get_new_handler ();
if (! handler)
_GLIBCXX_THROW_OR_ABORT(bad_alloc());
handler ();
}
return p;
}
Who guarantees that exception in constructor will free the allocated memory?
Upd: thanks to the commentators - actually I meant exception safety of new expression.
You are mixing in your question "new expression" and "operator new".
New expression is like this:
A* a = new A();
C++ language defines, that this expression is evaluated to something like this (over-simplified pseudo-code):As you can see - memory is dealocated if exception happens.
More detailed explanation:
For real generated code by compiler - refer here. You might notice call to operator delete - even if source code does not contain it:
Assembler: