开发者

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

开发者 https://www.devze.com 2022-12-28 01:21 出处:网络
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:

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?


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.


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.


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...!!!

0

精彩评论

暂无评论...
验证码 换一张
取 消