Home > Computing > new is abomination

new is abomination

If you’re seriously into writing code in C++, I strongly recommend watching the recordings from the Going Native 2013 conference.

One of the talks reminded me of the following guideline: Avoid using the new operator and never use the delete operator. It’s very easy to make a mistake when using them and the consequences are usually severe. Obviously you need to replace them with RAII (use constructors and destructors for acquiring and releasing resources, respectively).

The following seemingly innocuous example demonstrates the problem with the new operator:

class MyClass {
    OtherClass* ptr;
        : ptr( new OtherClass )
        // ... do some work here ...
    ~MyClass() {
        delete ptr;

What’s wrong here? The problem is not obvious at the first glance. If some code in the “do some work here” section throws an exception for whatever reason, the compiler has no way of knowing whether the object construction has been successfully finished or not, so the destructor’s body will never be invoked. If this happens, the object under ptr member will simply leak.

It may not seem serious at the first glance, but someone could spend weeks chasing down this leak, especially if the exception is thrown very rarely.

What scares me is that this approach to handling memory resources is very common…

What are the solutions?

  • If it’s a single object, try to make it a member of the class directly. This is  solution is particularly good if the parent class needs to be copyable.
  • If you have to allocate it for whatever reason, use std::unique_ptr in C++11 and std::auto_ptr C++98 (with caveats!). In this case the parent class must not be copyable, so better prevent that with some idiom, e.g. by deleting the copy constructor and assignment operator in C++11, or making the copy constructor and assignment operator private in C++98.
  • If you need a dynamically allocated array of objects, use std::vector.

The way of storing the object has to be carefully chosen depending on the usage scenario.

Categories: Computing
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: