C++ 智能指针和数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6713484/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 20:34:25  来源:igfitidea点击:

smart pointers and arrays

c++c++11smart-pointers

提问by helloworld922

How do smart pointers handle arrays? For example,

智能指针如何处理数组?例如,

void function(void)
{
    std::unique_ptr<int> my_array(new int[5]);
}

When my_arraygoes out of scope and gets destructed, does the entire integer array get re-claimed? Is only the first element of the array reclaimed? Or is there something else going on (such as undefined behavior)?

my_array超出范围并被破坏时,整个整数数组是否会被重新声明?是否只回收数组的第一个元素?或者还有其他事情发生(例如未定义的行为)?

回答by Alok Save

It will call delete[]and hence the entire array will be reclaimed but I believe you need to indicate that you are using an array form of unique_ptrby:

它将调用delete[],因此整个数组将被回收,但我相信您需要表明您使用的是数组形式unique_ptr

std::unique_ptr<int[]> my_array(new int[5]);

This is called as Partial Specializationof the unique_ptr.

这被称为局部特殊化unique_ptr

回答by Nathan Monteleone

Edit: This answer was wrong, as explained by the comments below. Here's what I originally said:

编辑:正如下面的评论所解释的那样,这个答案是错误的。这是我最初所说的:

I don't think std::unique_ptr knows to call delete[]. It effectively has an int* as a member -- when you delete an int* it's going to delete the entire array, so in this case you're fine.

The only purpose of the delete[] as opposed to a normal delete is that it calls the destructors of each element in the array. For primitive types it doesn't matter.

我不认为 std::unique_ptr 知道调用 delete[]。它实际上有一个 int* 作为成员——当你删除一个 int* 时,它会删除整个数组,所以在这种情况下你没问题。

delete[] 与普通删除相反的唯一目的是它调用数组中每个元素的析构函数。对于原始类型,这无关紧要。

I'm leaving it here because I learned something -- hope others will too.

我把它留在这里是因为我学到了一些东西——希望其他人也能。