C++ delete operator confusion [duplicate]
Possible Duplicate:
( POD )freeing memory : is delete[] equal to delete ?
char* pChar = new char[10];
delete pChar; // this should not work but it has same effect as
// delete[], WHY?
开发者_如何学运维 // I know this is illegal, but why does it work?
It may appear to have the same effect, but it does not. If your array type was an abstract data type (i.e. a class) then the destructors on the last nine elements would not have been called.
Because you got lucky. This is undefined behavior. One possibility for undefined behavior is that nothing bad seems to happen, even if something bad really did happen. You might not find out until later.
You can't count on being safe with primitive types. Read this (also linked by James Roth in a comment): https://isocpp.org/wiki/faq/freestore-mgmt#delete-array-built-ins
It doesn't work. It simply appears to work. The code that exhibits undefined behavior might appear to be "working" at the first sight, just like a program ridden with bugs might appear to "work fine" on a poorly selected test suite.
It's undefined behavior. And since "it works this time" falls into the category of "undefined", it can work on some platform, on some compiler. Still, it shouldn't be done. Have you tried deallocing an array of objects with destructors like that, and seeing if the destructors get called?
EDIT : According to your comments, you did...
In most versions of Microsoft Visual Studio this actually works correctly. However, there's no reason why this should be so, it's totally upto your platform.
The idea behind delete[] is that this is a special case in which size is not known at compile time, which the allocation framework might want to handle differently (and optimize the delete case).
Strictly speaking, delete pointerToBaseClass
also doesn't have size known at compile time, but this is solved by virtual table, and compiler knows that the class is polymorphic at compile time.
If you mishandle delete[], it may also have problems with tools replacing the allocator (debuggers, boundscheckers of all kinds, etcetc) and custom allocators your users may use.
精彩评论