[英]Is calling delete operator on a memory allocated by new[] operator undefined behavior?
I am pretty much sure it is but if I am interpreting correctly the standard (Section 18.6.1.2 new.delete.array) mentions that: 我非常确定,但是如果我正确解释了标准(第18.6.1.2节new.delete.array),则提到:
void operator delete[](void* ptr) noexcept; 无效运算符delete [](void * ptr)noexcept; pointer. 指针。
. 。 13 Default behavior: Calls operator delete(ptr) 13默认行为:调用运算符delete(ptr)
Since in its default behavior delete[] just calls its delete(ptr) equivalent why should it matter which version is called? 由于在默认行为中delete []仅调用其delete(ptr)等效项,为什么调用哪个版本无关紧要? I tried with a sample code to verify this and it crashes making it more evident that mismatching new[] and delete indeed lead to bad things 我尝试使用示例代码来验证这一点,它崩溃了,这很明显表明不匹配new []和delete确实会导致不良情况
#include <iostream>
#include <memory>
class foo{
public:
void bar(){
std::cout << "foo's bar" << std::endl;
}
~foo(){
std::cout << "foo dies after this" << std::endl;
}
};
int main() {
std::shared_ptr<foo> x(new foo[10]);
return 0;
}
How should the above quoted line from the standard be interpreted? 标准中上述引用的行应如何解释?
You're confusing the delete[]
expression with the function operator delete[]
. 您将delete[]
表达式与函数operator delete[]
混淆了。 When you write: 当你写:
delete[] p;
then the compiler issues code which will call destructors for all objects in the array pointed to by p
, and then call the deallocation function operator delete[]
with the argument p
. 然后,编译器发出代码,该代码将为p
指向的数组中的所有对象调用析构函数,然后使用参数p
调用释放函数operator delete[]
。 As per the documentation you've quoted, the default ::operator delete[]
calls ::operator delete
. 根据您引用的文档,默认的::operator delete[]
调用::operator delete
。 So the following calls to the deallocation functions are equivalent when default implementations are used: 因此,当使用默认实现时,以下对释放函数的调用是等效的:
::operator delete[] (p);
::operator delete(p);
But the following are not equivalent, because they do much more than just call the deallocation functions: 但是以下内容并不等效,因为它们所做的不仅仅是调用释放函数:
delete[] p;
delete p;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.