Skip to main content

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 function
void func (T*, U*);
int 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 function
void 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.

#include <new>
struct X {};

class C {
static void * operator new (size_t size); // typical overloaded new
static void operator delete (void *p, size_t size);
// A matter of style: declaration of size can be removed
// from the destructor above!

static void * operator new (size_t size, const X &x);
static void operator delete (void *p, const X &x);

static void * operator new (size_t size, std::nothrow_t) throw ();
static void operator delete (void *p, std::nothrow_t) throw ();

static void * operator new (size_t size, void *p); // placement new
static void operator delete (void *p, void *);
// In the above overloaded delete, signature appears redundant
// but it is necessary! Both pointer values are the same!

static void * operator new [] (size_t size); // Array new
static void operator delete [] (void *p); // Array delete

static void * operator new [] (size_t size, const X &x);
static void operator delete [] (void *p, const X &x);

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.


Nan Li said…

i am a c/c++ programmer, nice to know you. You can go to My Blog
Anonymous said…
Good info! Helped me solve a memory leak.

Popular Content

Unit Testing C++ Templates and Mock Injection Using Traits

Unit testing your template code comes up from time to time. (You test your templates, right?) Some templates are easy to test. No others. Sometimes it's not clear how to about injecting mock code into the template code that's under test. I've seen several reasons why code injection becomes challenging. Here I've outlined some examples below with roughly increasing code injection difficulty. Template accepts a type argument and an object of the same type by reference in constructor Template accepts a type argument. Makes a copy of the constructor argument or simply does not take one Template accepts a type argument and instantiates multiple interrelated templates without virtual functions Lets start with the easy ones. Template accepts a type argument and an object of the same type by reference in constructor This one appears straight-forward because the unit test simply instantiates the template under test with a mock type. Some assertion might be tested in

Covariance and Contravariance in C++ Standard Library

Covariance and Contravariance are concepts that come up often as you go deeper into generic programming. While designing a language that supports parametric polymorphism (e.g., templates in C++, generics in Java, C#), the language designer has a choice between Invariance, Covariance, and Contravariance when dealing with generic types. C++'s choice is "invariance". Let's look at an example. struct Vehicle {}; struct Car : Vehicle {}; std::vector<Vehicle *> vehicles; std::vector<Car *> cars; vehicles = cars; // Does not compile The above program does not compile because C++ templates are invariant. Of course, each time a C++ template is instantiated, the compiler creates a brand new type that uniquely represents that instantiation. Any other type to the same template creates another unique type that has nothing to do with the earlier one. Any two unrelated user-defined types in C++ can't be assigned to each-other by default. You have to provide a

Multi-dimensional arrays in C++11

What new can be said about multi-dimensional arrays in C++? As it turns out, quite a bit! With the advent of C++11, we get new standard library class std::array. We also get new language features, such as template aliases and variadic templates. So I'll talk about interesting ways in which they come together. It all started with a simple question of how to define a multi-dimensional std::array. It is a great example of deceptively simple things. Are the following the two arrays identical except that one is native and the other one is std::array? int native[3][4]; std::array<std::array<int, 3>, 4> arr; No! They are not. In fact, arr is more like an int[4][3]. Note the difference in the array subscripts. The native array is an array of 3 elements where every element is itself an array of 4 integers. 3 rows and 4 columns. If you want a std::array with the same layout, what you really need is: std::array<std::array<int, 4>, 3> arr; That's quite annoying for