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.
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 .
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.
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>();
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 .
The last line is an attempt to do a copy assignment operation, which is delete
d for std::unique_ptr
. You need to use the move-assignment operator:
m_collection[0] = std::move(np);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With