简体   繁体   English

返回唯一指针的STL容器

[英]Returning a STL container of unique pointers

I'm not knowledgeable about STL containers and their inner workings but is it valid to declare the following? 我不了解STL容器及其内部工作原理,但是声明以下内容是否有效?

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

From what I know, std::array<std::shared_ptr<Object>> p_object works but I get a compiler error when I try to declare an array with unique pointers. 据我所知, std::array<std::shared_ptr<Object>> p_object可以工作,但是当我尝试使用唯一指针声明数组时出现编译器错误。 Is this because the std::array tries to copy the unique pointers? 这是因为std :: array试图复制唯一指针吗? If I want a collection of unique pointers what STL container should I use? 如果我要收集唯一的指针,应该使用哪个STL容器? I read somewhere that its better to simply use raw pointers with STL containers. 我在某处读到,最好只对STL容器使用原始指针。 Is this true? 这是真的?

EDIT: 编辑:

I realized that the error is not originating from declaring the array but rather from the method: 我意识到错误不是源自声明数组而是源自方法:

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

I'm guessing that by returning an array of unique pointers I'm creating a copy of the unique pointers. 我猜想,通过返回唯一指针数组,我正在创建唯一指针的副本。 I had assumed RVO wouldn't create a copy. 我以为RVO不会创建副本。 How exactly should I rewrite this function? 我究竟应该如何重写此函数?

EDIT2 EDIT2

The error message reads 错误消息显示为

deleted function '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::unique_ptr<_Tp, _Tp_Deleter> = std::unique_ptr]' used here 删除的函数'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]'此处使用

'used here' referred to the array template class “在这里使用”指的是数组模板类

It is clearly not a good practice to put raw pointers in std containers. 将原始指针放在std容器中显然不是一个好习惯。 Your type is valid but you have somewhere an unwanted copy that is not authorized. 您的类型有效,但是某处有未经授权的不需要的副本。 You need to find that part of the code and force a move operation instead. 您需要找到代码的那一部分,然后强制执行移动操作。

on EDIT : you probably wants to return by reference like this : 在EDIT上:您可能希望通过引用返回,如下所示:

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

If you want to extract the values and remove them from the initial member, then force a move operation : 如果要提取值并将其从初始成员中删除,请强制执行移动操作:

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