Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot add a unique_ptr to a std::array

After searching through books and online until the onset of a big pain between my ears, I cannot figure out how to add a std::unique_ptr to a std::array.

The following is a class member:

std::array<std::unique_ptr<Media>, MAX_ELMS_NUM> m_collection;

In the .cpp file I am trying to add a new media pointer stuffed in a std::unique_ptr to the array:

Media* newMedia = CreateNewMedia(Media info stuff);
unique_ptr<Media> np(newMedia);
m_collection[0] = np;

Everything compiles except for the last line.

like image 317
Rodney Hamilton Avatar asked Mar 10 '16 02:03

Rodney Hamilton


People also ask

What happens when unique_ptr goes out of scope?

An​ unique_ptr has exclusive ownership of the object it points to and ​will destroy the object when the pointer goes out of scope. A unique_ptr explicitly prevents copying of its contained pointer. Instead, the std::move function has to be used to transfer ownership of the contained pointer to another unique_ptr .

What happens when you move a unique_ptr?

A unique_ptr can only be moved. This means that the ownership of the memory resource is transferred to another unique_ptr and the original unique_ptr no longer owns it. We recommend that you restrict an object to one owner, because multiple ownership adds complexity to the program logic.

How do you create a unique pointer array in C++?

If you want to create a unique_ptr , you can write: class Object { }; // unique_ptr auto ptr = std::make_unique<Object>(); auto intPtr = std::make_unique<int>(); // or shared_ptr auto shared = std::make_shared<Object>(); auto intShared = std::make_shared<int>();

What is unique_ ptr in c++?

Ownership. A unique pointer is a 1-to-1 relationship between a pointer ( p ) and its allocated object on the heap ( new int ). unique_ptr<int> p(new int); // p <--------> object. p owns the object and the object has only one owner, p .


2 Answers

The last line is an attempt to do a copy assignment operation, which is deleted for std::unique_ptr. You need to use the move-assignment operator:

m_collection[0] = std::move(np);
like image 113
KyleKnoepfel Avatar answered Sep 29 '22 05:09

KyleKnoepfel


You can't copy a unique_ptr, full stop. That's what "unique" means - there is only one unique_ptr pointing to the same object.

Now, you can assign a unique_ptr to a different one, but that clears the original one. Since it would be really confusing if a = b modified b, you have to specifically indicate that you want this, with std::move:

m_collection[0] = std::move(np);

After this line, m_collection[0] will point to the Media object, and np will be cleared.

like image 32
user253751 Avatar answered Sep 29 '22 05:09

user253751