3

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?
4

5 回答 5

12

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.

于 2010-06-29T20:21:29.453 回答
8

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

于 2010-06-29T20:21:10.967 回答
5

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.

于 2010-06-29T20:23:33.443 回答
1

这是未定义的行为。而且由于“这次可以工作”属于“未定义”的类别,它可以在某些平台上,在某些编译器上工作。不过,不应该这样做。您是否尝试过使用类似的析构函数释放对象数组,并查看析构函数是否被调用?

编辑:根据您的评论,您确实...

于 2010-06-29T20:26:32.233 回答
0

在大多数版本的 Microsoft Visual Studio 中,这实际上可以正常工作。但是,没有理由这样,这完全取决于您的平台。

delete[] 背后的想法是,这是一种在编译时大小未知的特殊情况,分配框架可能希望以不同的方式处理(并优化删除情况)。

严格来说,delete pointerToBaseClass在编译时也不知道大小,但这是通过虚拟表解决的,编译器在编译时知道该类是多态的。

如果您对 delete[] 处理不当,则替换分配器(调试器、各种边界检查器等)和用户可能使用的自定义分配器的工具也可能会出现问题。

于 2010-06-29T20:48:49.267 回答