【问题标题】:How are std::arrays of smart pointers initialized? [duplicate]智能指针的 std::arrays 是如何初始化的? [复制]
【发布时间】:2018-11-06 01:42:57
【问题描述】:

我目前尝试初始化以下数组,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 &,这很有意义。

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

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

那么,你是如何做到这一点的呢?这甚至是一回事吗?或者你根本不应该使用带有智能指针的 std::arrays 吗?

【问题讨论】:

  • std::array 无关紧要。您可以使用普通的unique_ptr&lt;Spot&gt; 并遇到相同的错误。
  • 不,链接不是关于是否使用make_unique,而是关于使用make_unique和直接使用unique_ptr的构造函数的区别。不,这不是将 STL 容器和智能指针一起使用,即使您是 OP 并且您以这种方式感知自己的问题。链接的问题解决了您的问题,因为您使用 new 表达式作为 make_unique 的参数。
  • 是的,我现在看到了,谢谢你的澄清

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


【解决方案1】:

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

std::make_unique<Spot>()

make_unique 调用new

【讨论】:

    猜你喜欢
    • 2022-12-16
    • 2012-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-07
    • 1970-01-01
    • 2015-10-03
    • 1970-01-01
    相关资源
    最近更新 更多