Click here to Skip to main content
Click here to Skip to main content
Alternative Tip

Tagged as

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

, 13 Aug 2011
Rate this:
Please Sign up or sign in to vote.
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)

Share

About the Author

BWake
Software Developer (Senior)
United States United States
No Biography provided

Comments and Discussions

 
GeneralReason for my vote of 5 Good Explanation Pinmemberryan20fun9-Aug-11 1:06 
GeneralThis is not an alternate tip. It's a comment. PinmvpJohn Simmons / outlaw programmer5-Aug-11 11:47 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140814.1 | Last Updated 13 Aug 2011
Article Copyright 2011 by BWake
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid