C++ tip 10: Know when to use delete and when to use delete[]

I want to share with you a nice little tip from Scott Meyers, author of Effective C++.

Let me ask you:

Do you know when to use delete and when to use delete[] ?

For example, is the following example correct?

std::string *myStrings=new std::string[10];

//...

delete myString;

You may assume that since we are calling delete, all of the objects created by new will be deallocated. Actually, only one of the 10 objects will be deallocated.

Using delete will only delete one single object. In the code above, we have an array of objects, thus the right way to delete those objects is by using delete [].

For example:

std::string *myStrings=new std::string[10];

//...

delete[] myString; //deletes an array of objects

So when you have a single object you use delete. When you have an array of objects you need to use delete[] as shown in the example below.

std::string *myName=new std::string;
std::string *myStrings=new std::string[10];

delete myName; //deletes an object
delete[] myString; //deletes an array of object.

You need to keep in mind when to use delete and delete[]. This is because using it in the wrong context will produce undefined behaviors.

For example, using delete[] on myName or using delete on myString will result in undefined behaviors.

So, Scott's tip is the following:

If you use [] in a new expression, you must use [] in the corresponding delete expression. If you don't use [] in a new expression, you must not use [] in the corresponding delete expression.

Sign up to my newsletter below to receive programming tips.

Harold Serrano

Computer Graphics Enthusiast. Currently developing a 3D Game Engine.