考虑:
delete new std :: string [2];
delete [] new std :: string;
每个人都知道第一个是错误的。如果第二个不是错误,我们就不需要两个不同的运算符。
现在考虑:
std :: unique_ptr <int> x (new int [2]);
std :: unique_ptr <int> y (new int);
x
是否知道使用 delete[]
而不是 delete
?
背景:当我认为指针的数组类型限定将是一种方便的语言功能时,这个问题浮现在我脑海中。
int *[] foo = new int [2]; // OK
int * bar = new int; // OK
delete [] foo; // OK
delete bar; // OK
foo = new int; // Compile error
bar = new int[2]; // Compile error
delete foo; // Compile error
delete [] bar; // Compile error
最佳答案
不幸的是,他们不知道要使用什么删除,因此他们使用 delete
.这就是为什么对于每个智能指针,我们都有一个智能数组对应项。
std::shared_ptr uses delete
std::shared_array uses delete[]
所以,你的线
std :: unique_ptr <int> x (new int [2]);
实际上会导致未定义的行为。
顺便说一句,如果你写
std :: unique_ptr<int[]> p(new int[2]);
^^
然后 delete[]
将被使用,因为您已明确要求。但是,以下行仍将是 UB。
std :: unique_ptr<int[]> p(new int);
他们无法选择的原因delete
和 delete[]
是new int
和 new int[2]
是完全相同的类型 - int*
.
Here是在 smart_ptr<void>
的情况下使用正确删除器的相关问题和 smart_ptr<Base>
当Base
没有虚拟析构函数。
关于c++ - 智能指针如何在 delete 和 delete[] 之间进行选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8940931/