Click here to Skip to main content
15,881,204 members
Articles / General Programming
Alternative
Tip/Trick

C++ Tip: Aware of the confusion between delete with delete[]

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
13 Aug 2011CPOL 7K   3   3
It is a bad idea to treat built-in types differently than programmer defined classes. If you delete a dynamically allocated array of a built-in type without the brackets the memory buffer may go away just fine. This is not guaranteed. The VS2008 runtime throws an exception. There is a...
It is a bad idea to treat built-in types differently than programmer defined classes.

If you delete a dynamically allocated array of a built-in type without the brackets the memory buffer may go away just fine. This is not guaranteed. The VS2008 runtime throws an exception.

There is a more important difference.

The delete array operator delete [] calls the destructor on each of the array elements. The singleton delete does not. it will only call the destructor on the first.

If the compiler and testing don't catch it you could wind up with a nasty bug. Your time and your users' time cost more than any trivial possible runtime difference, which the compiler will optimize away anyhow. Don't give yourself bad habits. Treat built-in types like any other.

This test program shows the destructor being called for each array element on delete [].

class test
{
private:
    static int m_instance;
public:
    test() { ++m_instance; }
    ~test ()
    {
        printf ( "test destructor %d\n", m_instance-- );
    }
};

int test::m_instance = 0;

int main ()
{
    test *t = new test[10];

    delete [] t; // calls the destructor ten times
    t = NULL;

    t = new test[10];
    delete t;    // undefined behavior
    t = NULL;

}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Generalthanks Pin
Southmountain11-Jan-20 10:36
Southmountain11-Jan-20 10:36 
GeneralReason for my vote of 5 Good Explanation Pin
ryan20fun9-Aug-11 1:06
ryan20fun9-Aug-11 1:06 
GeneralThis is not an alternate tip. It's a comment. Pin
#realJSOP5-Aug-11 11:47
mve#realJSOP5-Aug-11 11:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.