如何初始化 std::unique_ptr<std::unique_ptr<T>[]>?

Vik*_*xén 3 c++ smart-pointers unique-ptr data-structures c++14

我的班级有这个成员:

static std::unique_ptr<std::unique_ptr<ICommand>[]> changestatecommands;
Run Code Online (Sandbox Code Playgroud)

我找不到初始化它的正确方法。我希望数组被初始化,但元素未初始化,所以我可以随时编写如下内容:

changestatecommands[i] = std::make_unique<ICommand>();
Run Code Online (Sandbox Code Playgroud)

数组是在声明时立即初始化还是在运行时稍后初始化都没有关系。最理想的是,我想知道如何做到这两点。

JeJ*_*eJo 6

如何初始化std::unique_ptr<std::unique_ptr<ICommand>[]>

像这样

#include <memory>

std::unique_ptr<std::unique_ptr<ICommand>[]> changestatecommands{
    new std::unique_ptr<ICommand>[10]{nullptr}
};

// or using a type alias
using UPtrICommand = std::unique_ptr<ICommand>;
std::unique_ptr<UPtrICommand[]> changestatecommands{ new UPtrICommand[10]{nullptr} };

//or like @t.niese mentioned
using UPtrICommand = std::unique_ptr<ICommand>;
auto changestatecommands{ std::make_unique<UPtrICommand[]>(10) };
Run Code Online (Sandbox Code Playgroud)

但是,正如其他人提到的,请考虑替代方案,例如

std::vector<std::unique_ptr<ICommand>>  // credits  @t.niese
Run Code Online (Sandbox Code Playgroud)

在得出上述结论之前。