对std::unique_ptr数组的赋值

assignment to an array of std::unique_ptr

本文关键字:数组 ptr 赋值 std unique      更新时间:2023-10-16
struct MyStruct
{
int x = 0;
}
std::array<std::unique_ptr<MyStruct>, 10> Arr;
// Arr[0] = ?

将对象分配给这样的数组的语法是什么?我的推荐人。

费翔回答:

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>()
};

为了避免移动任务。