如何制作一个容纳unique_ptrs的数组?

How to make an array that holds unique_ptrs?

本文关键字:unique ptrs 数组 何制作 一个      更新时间:2023-10-16

我假设下面的代码是数组的unique_ptr(也就是不是我想要的(

std::unique_ptr<int[]> arr;
arr = std::make_unique<int[]> (5);
arr[0] = *new int(1);
delete &arr[0]; // malloc error, want to avoid "delete"

但是,我想要一个容纳这样unique_ptrs的数组......

std::unique_ptr<int> arr2 [];       //Error, requires explicit size
arr2 = std::make_unique<int> [5];   //Desirable, does not compile
arr2[0] = std::make_unique<int>(1); //Desirable, does not compile

如何制作一系列unique_ptrs?如果这是不可能的,那么我该如何处理malloc错误?

你想要一个保存unique_ptr的数组(如标题所示(,还是一个保存数组的unique_ptr(如你的示例中(?


如果您想要的unique_ptrs 数组,则

std::vector<std::unique_ptr<int>>

std::array<std::unique_ptr<int>, 3>;

(例如(将完成这项工作。


如果您正在寻找持有数组的unique_ptr,那么unique_ptr<int[]>将起作用(有部分unique_ptr专用来支持它(,尽管您不能使用std::make_unique并且需要自己调用operator new[]

std::unique_ptr<int[]> p{new int[42]};

但是,如果您认为您需要这个,那么您最有可能真正想要的是std::vector,我强烈建议使用它。

简短的回答:使用向量。它们更容易使用,您不必显式分配内存。您还应该使用 typedefs 来简化语法。

typedef unique_ptr<int> intPtr;
vector<intPtr> vec;
vec.push_back(make_unique<int>(69));
auto myIntPtr = make_unique<int>(16);
vec.push_back(move(myIntPtr)); // unique ptrs cannot be copied, must be moved
unique_ptr<int[5]> p1; // valid syntax
std::unique_ptr<int[]> arr;
arr = std::make_unique<int[]> (5);

此时,您有一个unique_ptrint数组。这听起来正是您想要的。

arr[0] = *new int(1);

但这是值得怀疑的。它动态分配单个int,将 1 分配给分配的int,然后将分配int的值 1 分配给元素 0 的数组中。分配的int被挂起,没有任何指向它,现在非常难以"删除"。这是内存泄漏。

delete &arr[0]; // malloc error, want to avoid "delete"

正如你所看到的,这是致命的。delete不是试图delete泄漏的int,而是用一个指向存储在unique_ptr中的数组的指针来调用。最终,unique_ptrwill try to删除数组并失败,因为它已经消失了。

根据评论,OP打算

std::unique_ptr<int*[]> arr;
arr = std::make_unique<int*[]> (5);
arr[0] = new int(1);
delete arr[0]; 

但我想说服他们放弃这个想法。让我们看看它们的最终目标:模板化类

template <class TYPE>
class MyVector
{
std::unique_ptr<TYPE[]> arr; // array of whatever type
public:
MyVector(size_t size): arr(std::make_unique<TYPE[]> (size))
{
}
TYPE& operator[](size_t index)
{
return arr[index];
}
// note the complete lack of growing, shrinking and other vector goodness
// as they are not needed for this example.
};

我们几乎可以将这个类用于任何东西。

int main()
{
// vector of int
MyVector<int> vec(5);
vec[0] = 1;
// vector of pointer to int (yuck)
MyVector<int*> vec2(5);
vec2[0] = new int(1);
delete vec2[0];
// vector of smart pointer to int (also yuck, but less yuck)
MyVector<std::unique_ptr<int>> vec3(5);
vec3[0] = std::make_unique<int>(1);
// vector of std::string
MyVector<std::string> vec4(5);
vec4[0] = "I am the very model of a modern major general...";
}

如果向量的用户希望它包含指针,他们可以这样说。没有理由强制用户使用指针。