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

How to initialize std::unique_ptr<std::unique_ptr<T>[]>?

我的class有这个会员:

static std::unique_ptr<std::unique_ptr<ICommand>[]> changestatecommands;

而且我找不到初始化它的正确方法。我希望数组被初始化,但元素未初始化,所以我可以随时写这样的东西:

changestatecommands[i] = std::make_unique<ICommand>();

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

How to initialize 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) };

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

std::vector<std::unique_ptr<ICommand>>  // credits  @t.niese

在得出上述结论之前。