如何初始化std ::智能指针数组?

时间:2018-05-27 07:07:27

标签: c++ stl std smart-pointers unique-ptr

我目前尝试初始化以下数组,Spot是一个在别处定义的类:

static const int WIDTH = 7;
static const int HEIGHT = 6;
std::array<std::array<std::unique_ptr<Spot>, WIDTH>, HEIGHT> field;

尝试初始化时:

    for (int i = 0; i < HEIGHT; i++) {
    for (int j = 0; j < WIDTH; j++) { 
        field.at(i).at(j) = std::make_unique<Spot>(new Spot());
    }
}

它声明Spot *无法转换为const Spot&amp;,这非常有意义。

谷歌在这里并没有真正的帮助,因为问题要么处理

std::unique_ptr<T> [] or
std::uniqe_ptr<std::array<T>> but not with 
std::array<std::unique_ptr<T>> 

那么,你是如何实现这一目标的?这甚至是一件事吗?或者你不应该使用带有智能指针的std :: arrays吗?

1 个答案:

答案 0 :(得分:1)

make_unique调用错误:您必须转发用于初始化Spot的参数(在本例中为none)

std::make_unique<Spot>()

最多make_unique可以拨打new