分配给 std::unique_ptr 的数组
assignment to an array of std::unique_ptr
struct MyStruct
{
int x = 0;
}
std::array<std::unique_ptr<MyStruct>, 10> Arr;
// Arr[0] = ?
将对象分配给此类数组的语法是什么? My reference.
费翔回答:
Arr[0].reset(new MyStruct);
雷米·勒博回答:
Arr[0] = std::make_unique<MyStruct>(); // Since C++14
或者
std::array<std::unique_ptr<MyStruct>, 10> Arr {
std::make_unique<MyStruct>(),
std::make_unique<MyStruct>(),
std::make_unique<MyStruct>(),
std::make_unique<MyStruct>(),
std::make_unique<MyStruct>(),
std::make_unique<MyStruct>(),
std::make_unique<MyStruct>(),
std::make_unique<MyStruct>(),
std::make_unique<MyStruct>(),
std::make_unique<MyStruct>()
};
避免移动赋值。
struct MyStruct
{
int x = 0;
}
std::array<std::unique_ptr<MyStruct>, 10> Arr;
// Arr[0] = ?
将对象分配给此类数组的语法是什么? My reference.
费翔回答:
Arr[0].reset(new MyStruct);
雷米·勒博回答:
Arr[0] = std::make_unique<MyStruct>(); // Since C++14
或者
std::array<std::unique_ptr<MyStruct>, 10> Arr {
std::make_unique<MyStruct>(),
std::make_unique<MyStruct>(),
std::make_unique<MyStruct>(),
std::make_unique<MyStruct>(),
std::make_unique<MyStruct>(),
std::make_unique<MyStruct>(),
std::make_unique<MyStruct>(),
std::make_unique<MyStruct>(),
std::make_unique<MyStruct>(),
std::make_unique<MyStruct>()
};
避免移动赋值。