简体   繁体   中英

ANSI C++: Differences between delete and delete[]

I was looking a snipset of code:

    int* ip;
    ip = new int[100];
    delete ip;

The example above states that:

This code will work with many compilers, but it should instead read:

    int* ip;
    ip = new int[100];
    delete [] ip;

Is this indeed the case?

I use the compiler "Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 11.00.7022 for 80x86" and does not complain (first example) while compiling. At runtime the pointer is set to NULL .

Do other compilers behave differently? Can a compiler not complain and issues can appear at runtime?

You should always use delete [] when killing off an array, because it handles calling all the destructors on the contents. I think the reason why you're getting away with it here is that the int type doesn't have a destructor, but when you move to making arrays of objects with destructors, you'll really see the difference.

Which is a good argument for always using std::vector instead, of course. That gets all this stuff right for you.

There is really no way for the compiler to produce an error in this circumstance - the type of the pointer produced by new and new[] is the same. Certainly, the C++ Standard does not require any diagnostic for this situation. However, your first code snippet is incorrect for all compilers, and will lead to undefined behaviour - don't be tempted to do it because the compiler doesn't complain.

In this case, you MUST use delete [] since ip is an array. Anyway, the compiler will never give you an error (it might give you a warning), but you can get runtime errors.

The C++ spec requires you to use delete [] when deleting an array, and if you're worried about cross compiler compatibility or your code working with future versions of the same compiler then you should use it.

Your runtime may choose to allocate memory differently for arrays than it does for single objects. By not correctly indicating what your deleting you run the risk that your code may fail to release memory correctly.

So, basically, call the right form...!!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM