Вопрос

I'm not knowledgeable about STL containers and their inner workings but is it valid to declare the following?

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. Is this because the std::array tries to copy the unique pointers? If I want a collection of unique pointers what STL container should I use? I read somewhere that its better to simply use raw pointers with STL containers. 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. How exactly should I rewrite this function?

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

'used here' referred to the array template class

Это было полезно?

Решение

It is clearly not a good practice to put raw pointers in std containers. 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 :

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 с атрибуция
Не связан с StackOverflow
scroll top