我班有这个成员:
static std::unique_ptr<std::unique_ptr<ICommand>[]> changestatecommands;
我找不到正确的方法来初始化它。我希望数组被初始化,但元素未初始化,因此我可以随时编写如下内容:
changestatecommands[i] = std::make_unique<ICommand>();
数组是在声明时立即初始化还是在运行时稍后初始化都没有关系。理想情况下,我想知道如何同时做。
如何初始化
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
在得出上述结论之前。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句