std::arrays个智能指针是如何初始化的?
How are std::arrays of smart pointers initialized?
我目前尝试初始化以下数组,Spot 是在别处定义的 class:
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 &,这很有道理。
Google 在这里并没有多大帮助,因为问题要么涉及
std::unique_ptr<T> [] or
std::uniqe_ptr<std::array<T>> but not with
std::array<std::unique_ptr<T>>
那么,你是如何实现的呢?那是一回事吗?还是您根本不应该将 std::arrays 与智能指针一起使用?
make_unique
调用是错误的:您必须将用于初始化 Spot
的参数转发给它(none,在这种情况下)
std::make_unique<Spot>()
由make_unique
调用new
。
我目前尝试初始化以下数组,Spot 是在别处定义的 class:
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 &,这很有道理。
Google 在这里并没有多大帮助,因为问题要么涉及
std::unique_ptr<T> [] or
std::uniqe_ptr<std::array<T>> but not with
std::array<std::unique_ptr<T>>
那么,你是如何实现的呢?那是一回事吗?还是您根本不应该将 std::arrays 与智能指针一起使用?
make_unique
调用是错误的:您必须将用于初始化 Spot
的参数转发给它(none,在这种情况下)
std::make_unique<Spot>()
由make_unique
调用new
。