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

3

我的类有这个成员:

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

我无法找到正确的初始化方式。我希望数组被初始化,但元素未被初始化,这样我可以随时像这样写入内容:

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

数组是在声明时立即初始化还是在运行时稍后初始化都无关紧要。我希望知道如何同时执行这两个操作。


为什么不使用简单的指针向量,例如 std::vector<ICommand*>(或者如果您需要所有权语义,则使用 std::vector<std::unique_ptr<ICommand>>)? - Some programmer dude
6
为什么您不使用std::vector<std::unique_ptr<ICommand>> - t.niese
2
我认为你使用unique_ptr[]存在明显的不利之处。 - Fantastic Mr Fox
1
更多的是避免使用C风格数组(std::unique_ptr<ICommand>[]),而是使用std容器。 - t.niese
每当你有关于C++的问题时,其中一个最先查找的地方就是CPP参考文献。请看这里的情况(2):https://en.cppreference.com/w/cpp/memory/unique_ptr/make_unique。 - Phil1970
显示剩余3条评论
1个回答

6
如何初始化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

在得出以上结论之前。


1
我会使用 std::make_unique<std::unique_ptr<ICommand>[]>(10),再结合 autoauto changestatecommands = std::make_unique<std::unique_ptr<ICommand>[]>(10) - t.niese
@t.niese 也可以。让我把它添加到答案中。 - JeJo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接