如何制作一个包含unique_ptrs的数组?

时间:2017-07-28 18:50:32

标签: c++ arrays c++14 unique-ptr

我假设下面的代码是一个数组的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错误呢?

3 个答案:

答案 0 :(得分:1)

简答:使用载体。它们更容易使用,您不必明确分配内存。您还应该使用typedef来简化语法。

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

答案 1 :(得分:1)

您想要一个包含unique_ptr的数组(如标题中所示),还是一个持有数组的unique_ptr(如示例所示)?

如果你想要一个unique_ptr的数组,那么

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

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

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

如果持有数组的unique_ptr是您所追求的,那么unique_ptr<int[]>将有效(有partial specialisation of unique_ptr to support it),但您无法使用std::make_unique并且需要自己致电operator new[]

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

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

答案 2 :(得分:0)

std::unique_ptr<int[]> arr;
arr = std::make_unique<int[]> (5);

此时您的unique_ptr数组为int。这听起来像是你想要的。

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

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

int

正如你所见,这是致命的。我没有尝试delete &arr[0]; // malloc error, want to avoid "delete" 泄漏的delete,而是使用指向存储在int中的数组的指针调用delete。最终,unique_ptr unique_ptr删除了数组并因为它已经消失而失败。

基于评论,OP打算

will try to

但我想谈谈这个想法。让我们来看看他们的最终目标:模板化的课程

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.
};

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

相关问题