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.


Kenan Lee 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 posts from this blog

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 two r…

Understanding Fold Expressions

C++17 has an interesting new feature called fold expressions. Fold expressions offer a compact syntax to apply a binary operation to the elements of a parameter pack. Here’s an example. template <typename... Args> auto addall(Args... args) { return (... + args); } addall(1,2,3,4,5); // returns 15. This particular example is a unary left fold. It's equivalent to ((((1+2)+3)+4)+5). It reduces/folds the parameter pack of integers into a single integer by applying the binary operator successively. It's unary because it does not explicitly specify an init (a.k.a. identity) argument. So, let add it. template <typename... Args> auto addall(Args... args) { return (0 + ... + args); } addall(1,2,3,4,5); // returns 15. This version of addall is a binary left fold. The init argument is 0 and it's redundant (in this case). That's because this fold expression is equivalent to (((((0+1)+2)+3)+4)+5). Explicit identity elements will come in handy a little la…

Folding Monadic Functions

In the previous two blog posts (Understanding Fold Expressions and Folding Functions) we looked at the basic usage of C++17 fold expressions and how simple functions can be folded to create a composite one. We’ll continue our stride and see how "embellished" functions may be composed in fold expressions.

First, let me define what I mean by embellished functions. Instead of just returning a simple value, these functions are going to return a generic container of the desired value. The choice of container is very broad but not arbitrary. There are some constraints on the container and once you select a generic container, all functions must return values of the same container. Let's begin with std::vector.
// Hide the allocator template argument of std::vector. // It causes problems and is irrelevant here. template <class T> struct Vector : std::vector<T> {}; struct Continent { }; struct Country { }; struct State { }; struct City { }; auto get_countries…