What to do when an exception is thrown on the initialization list when allocating memory for a raw pointer? The situation is easy if your class only has one raw pointer member, but it gets complicated with two or more. Here’s a code example that’s guaranteed to leak memory if the second new int throws an exception (because the destructor will not be called):

There is no way to free the memory allocated to p1 if p2(new int) throws! Let’s build on my previous example and see what happens if we use a function try-catch block on the constructor:

Still no good! Because accessing p1 and p2 in the catch block leads to undefined behavior. See here.

The only way to guarantee correct behavior is to use smart pointers. This works because 1) the initialization list allocates in pre-defined order (the order of member declaration) and 2) the destructors of already created members will be called. Here’s the correct way of allocating multiple pointers:

This is guaranteed to do proper cleanup if the second make_unique<int>() throws std::bad_alloc 🙂

Complete listing (bad_pointer.cpp):

Leave a Reply