我得到了以下代码:
T *p = new T[10];
delete p;
我想应该是delete [] p。我在T=int类型上试了一下,没有报错。然后我创建了一个简单的类,exception。有什么明确的解释吗?
T *p = 0;
delete p;
他们怎么了? [我查了一下,好像delete p虽然会报错,但是程序恢复是因为编译器一开始就认为p==0,所以这个报错无所谓。]
最佳答案
是的,
你应该调用 delete [] p;
Any clear explanation?
这是未定义的行为:
- 如果分配是通过
new []
调用delete
- 对非动态分配的指针调用
delete
。
请注意,Undefined Behavior 意味着任何事情都可能发生,它并不强制要求崩溃。它只是意味着您的程序可以显示任何行为(包括按预期工作)。
在NULL
指针上调用delete
是完全有效的。该标准允许这样做。 delete
运算符在内部采用了它的核心,调用者不必为 NULL
检查而烦恼。
引用资料:
C++03 标准 §3.7.4.2-3:
If a deallocation function terminates by throwing an exception, the behavior is undefined. The value of the first argument supplied to a deallocation function may be a null pointer value; if so, and if the deallocation function is one supplied in the standard library, the call has no effect. Otherwise, the value supplied to operator
delete(void*)
in the standard library shall be one of the values returned by a previous invocation of either operatornew(std::size_t)
oroperator new(std::size_t, const std::nothrow_-t&)
in the standard library, and the value supplied to operatordelete[](void*)
in the standard library shall be one of the values returned by a previous invocation of eitheroperator new[](std::size_t)
oroperator new[](std::size_t, const std::nothrow_t&)
in the standard library.
关于C++:以下代码有什么问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14425188/