我类有这个成员:
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
在得出上述结论之前。
关于c++ - 如何初始化 std::unique_ptr<std::unique_ptr<T>[]>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59501659/