64,660
社区成员
发帖
与我相关
我的任务
分享
/*实在是看不下去了。这几天到处有人说这个。于是转篇文章给大家看看。
有哪一本书说过可以不带[]吗?(C++ Primer/The C++ Programming Language/C++ Standard)
请找出来看看!
[16.13] Can I drop the [] when deleteing array of some built-in type (char, int, etc)?
No!
Sometimes programmers think that the [] in the delete[] p only exists so the compiler will call the appropriate destructors for all elements in the array. Because of this reasoning, they assume that an array of some built-in type such as char or int can be deleted without the []. E.g., they assume the following is valid code:
void userCode(int n)
{
char* p = new char[n];
...
delete p; // ← ERROR! Should be delete[] p !
}
But the above code is wrong, and it can cause a disaster at runtime. In particular, the code that's called for delete p is operator delete(void*), but the code that's called for delete[] p is operator delete[](void*). The default behavior for the latter is to call the former, but users are allowed to replace the latter with a different behavior (in which case they would normally also replace the corresponding new code in operator new[](size_t)). If they replaced the delete[] code so it wasn't compatible with the delete code, and you called the wrong one (i.e., if you said delete p rather than delete[] p), you could end up with a disaster at runtime.
#include <stdio.h>
class A
{
public:
~A() {};
int n;
};
int main()
{
A* arr = new A[8];
printf("before delete\n");
delete arr;
printf("after delete\n");
return 0;
}
int arr[10];
arr[10] = 100;