【发布时间】: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<Spot>并遇到相同的错误。 -
不,链接不是关于是否使用
make_unique,而是关于使用make_unique和直接使用unique_ptr的构造函数的区别。不,这不是将 STL 容器和智能指针一起使用,即使您是 OP 并且您以这种方式感知自己的问题。链接的问题解决了您的问题,因为您使用new表达式作为make_unique的参数。 -
是的,我现在看到了,谢谢你的澄清
标签: c++ stl std smart-pointers unique-ptr