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

标签 c++ data-structures c++14 smart-pointers unique-ptr

我类有这个成员:

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/

相关文章:

Python如何使用defaultdict创建列表字典的字典

java - 我应该使用哪种数据结构?

c++ - 为什么clang拒绝可变参数模板 friend 功能

c++ - std::forward_list::insert_after 线程安全

c++ - 执行 memcpy 时内存泄漏

c++ - 内存布局 C++ 对象

c++ - Linux (gcc 5.4) 中是否有任何特定于 Windows 的 SecureZeroMemory 等效库函数可用?

c++ - Listing Observer 没有更新 "see"

c - 从文件导入链表数据时出现 fscanf 错误

c++ - 正确编写基于范围的构造函数