Calling new
on a throwing constructor will not leak memory, since apparently all this is handled by the new operator. I'd assume that for user-defined new/delete operators this doesn't happen out of the box, but valgrind
reports no memory leaks on my test programs (just that the process is terminating):
#include <iostream>
struct Widget
{
Widget()
{
std::cout << "\tctor\n";
throw "up";
}
void *operator new(size_t sz)
{
std::cout << "\tnew " << sz << " bytes\n";
return malloc(sz);
}
void operator delete(void *p)
{
std::cout << "\tdelete\n";
free(p);
}
};
int main()
{
auto a = new Widget;
return 0;
}
How is memory deallocated in my case? Is the memory guaranteed to be deallocated when a constructor throws in the default new operator as well?