簡體   English   中英

返回唯一指針的STL容器

[英]Returning a STL container of unique pointers

我不了解STL容器及其內部工作原理,但是聲明以下內容是否有效?

std::array<std::unique_ptr<Object>, 4> p_object;

據我所知, std::array<std::shared_ptr<Object>> p_object可以工作,但是當我嘗試使用唯一指針聲明數組時出現編譯器錯誤。 這是因為std :: array試圖復制唯一指針嗎? 如果我要收集唯一的指針,應該使用哪個STL容器? 我在某處讀到,最好只對STL容器使用原始指針。 這是真的?

編輯:

我意識到錯誤不是源自聲明數組而是源自方法:

std::array<std::unique_ptr<tp::QuadTree>, 4> get_children(){ return children; }

我猜想,通過返回唯一指針數組,我正在創建唯一指針的副本。 我以為RVO不會創建副本。 我究竟應該如何重寫此函數?

EDIT2

錯誤消息顯示為

刪除的函數'std :: unique_ptr <_Tp,_Tp_Deleter> :: unique_ptr(const std :: unique_ptr <_Tp,_Tp_Deleter>&)[with _Tp = tp :: QuadTree,_Tp_Deleter = std :: default_delete,std: ,_Tp_Deleter> = std :: unique_ptr]'此處使用

“在這里使用”指的是數組模板類

將原始指針放在std容器中顯然不是一個好習慣。 您的類型有效,但是某處有未經授權的不需要的副本。 您需要找到代碼的那一部分,然后強制執行移動操作。

在EDIT上:您可能希望通過引用返回,如下所示:

std::array<std::unique_ptr<tp::QuadTree>, 4> const & get_children() const { return children; }

如果要提取值並將其從初始成員中刪除,請強制執行移動操作:

std::array<std::unique_ptr<tp::QuadTree>, 4> extract_children(){ return std::move(children); }

暫無
暫無

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

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