A blog on various topics in C++ programming including language features, standards, idioms, design patterns, functional, and OO programming.

Tuesday, April 24, 2007

new, delete, custom memory allocation, and exception safety

This post will hopefully push you ahead to a higher level of expertise in memory management mechanics of C++ and exception safety. Here we go...

Some warm-up:

Consider a functionvoid func (T*, U*);andint main() { func (new T, new U); // line 1}Calling the function like in line 1 is a bad idea because parameter evaluation sequence is not standard and therefore it memory allocation of second new (it could T or U) fails, we have a blatant memory leak.

What to do? Lets use our silver bullet: auto_ptr! but it fails too for the same reasons. Consider a functionvoid func (std::auto_ptr <T>, std::auto_ptr <U>);

Now it is possible that, even before any auto_ptrs are constructed, new may throw or a constructor may throw and all efforts go in vain. Details can be found in Hurb Sutter's More Excetional C++: Item 20-21.

So we should separate the allocation and the function call.auto_ptr <T> t1 = new T; auto_ptr <U> u1 = new U; func (t1, u1);

That's no better either!

Now if func throws some exception X, there is no way to retrieve the objects pointed by t1 and u1 because by the time control flow reaches a catch block, the two pass-by-value auto_ptr parameters deleted the free store already! Never pass auto_ptrs by value if a function can throw. BTW, returning auto_ptrs by value is a good idea for factory and clone like functions.

Enough of warm-up. Lets do some real cardiac exercise!

Note: If the constructor of a dynamically allocated object throws an exception then C++ reclaims the allocated memory automatically by invoking delete automatically. It is a very good thing.

If you have one or more overloaded new operators in your class, you should have overloaded delete operator having exactly matching signature. Exactly matching signature part is important because if the constructor that is called after successful completion of your overloaded new throws then C++ automatically invokes the corresponding overloaded delete operator that has exactly the same signature to reclaim the memory. I have given declarations of some possible overloaded new and their corresponding delete couterparts.

int main (void){C *c = new (std::nothrow) C;// Here, if the constructor of C throws then the nothrow // overloaded delete will be called automatically.c->~C(); // Explicit destructor invocation because delete c does not help.C::operator delete (c, std::nothrow); // Free up the memory.}This post was motivated by Herb Sutter's Exceptional C++: Item 36.