c++ - 智能指针如何在 delete 和 delete[] 之间进行选择?

标签 c++ c++11 shared-ptr smart-pointers delete-operator

考虑:

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);

他们无法选择的原因deletedelete[]new intnew int[2]是完全相同的类型 - int* .

Here是在 smart_ptr<void> 的情况下使用正确删除器的相关问题和 smart_ptr<Base>Base没有虚拟析构函数。

关于c++ - 智能指针如何在 delete 和 delete[] 之间进行选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8940931/

相关文章:

c++ - new 表达式中详细类型说明符的条件表达式解析错误

c++ - 是否可以为 boost::make_iterator_range 起别名?

c++ - 返回 std::shared_ptr 的 vector 是否安全?

c++ - Eclipse 中的 Crypto++ 未定义引用

c++ - 每个类数据的 C++ 习惯用法,无需虚拟 getter 方法即可访问

c++ - For-loop 或 std::any_of,我应该使用哪一个?

c++ - 树莓派工具链上的 std::shared_future

c++ - 使用 boost::shared_ptr 的集合中的不同模板类

c++ - 自动删除发送给异步函数/io_service的容器

c++ - 为什么 C++ 允许您在初始定义中引用已声明的变量?