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

维克多·阿克森(ViktorAxén)

我班有这个成员:

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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

调整大小std :: vector <std :: unique_ptr <T >>的性能

std :: auto_ptr到std :: unique_ptr

为什么std :: shared_ptr <T> = std :: unique_ptr <T []>可以编译,而std :: shared_ptr <T []> = std :: unique_ptr <T []>不可以编译?

参数std :: unique_ptr <T> &&的std :: move或std :: forward

std :: list <std :: unique_ptr>:空的初始化列表与默认构造函数

std :: unique_ptr :: release()与std :: move()

指向std :: unique_ptr的内容

在gcc 6中实现std :: unique_ptr <T []> :: reset

std :: unique_ptr和QObject :: deleteLater

返回对std :: unique_ptr的引用的原因

使用std :: unique_ptr <T>&代替std :: unique_ptr <T>有什么优势吗?

通过unique_ptr访问std :: array

从初始化列表构造std :: map <T,unique_ptr <S >>时出错

is_assignable和std :: unique_ptr

std :: unique_ptr与std :: map

将std :: vector <std :: unique_ptr <T >>分配给另一个std :: vector <std :: unique_ptr <T >>

初始化std :: unique_ptr作为原始数组指针的初始化

无法使用std :: unique_ptr初始化指针

std :: unique_ptr构造函数的行为

还有什么更好的替代std :: vector <std :: unique_ptr <T >>吗?

将std :: unique_ptr <Derived>转换为std :: unique_ptr <Base>

延迟初始化std :: unique_ptr

std :: unique_ptr <T>而不在堆上分配内存

std :: vector <unique_ptr <class T >>的动态初始化

std :: unique_ptr constexpr构造函数

从std :: unique_ptr <Dervied>转换为std :: unique_ptr <Base>的成本是多少?

对 std::unique_ptr 数组的赋值

在 Qt 上使用 std::unique_ptr

使用 std::unique_ptr<T>::unique_ptr` 在 Visual Studio 2013 中构建错误