C++:以下代码有什么问题吗?

标签 c++ templates pointers memory-management memory-leaks

我得到了以下代码:

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 operator new(std::size_t) or operator new(std::size_t, const std::nothrow_-t&) in the standard library, and the value supplied to operator delete[](void*) in the standard library shall be one of the values returned by a previous invocation of either operator new[](std::size_t) or operator new[](std::size_t, const std::nothrow_t&) in the standard library.

关于C++:以下代码有什么问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14425188/

相关文章:

c++ - 如果我删除指向节点的指针数组,节点本身会被删除吗?

c++ - 使用 GCC 洗牌巨大位 vector 的最有效方法是什么

c++ - 我可以避免由特定类定义的限定名称吗?

c++ - 如何重新定位/调整屏幕上的资源?

python - 扫描特定属性的后代模板命名空间

c++ - 链接模板类函数

c++ - 将基类的引用传递给另一个函数

c++ - 使用可变函数参数泛化 is_detected

c# - C# 中的非托管句柄,我需要释放还是销毁?

.net - 尝试读取或写入 protected 内存