簡體   English   中英

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

[英]How to initialize std::unique_ptr<std::unique_ptr<T>[]>?

我的班級有這個成員:

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

在得出上述結論之前。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM