Rodney Hamilton
Rodney Hamilton

Reputation: 51

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.

Upvotes: 5

Views: 460

Answers (3)

songyuanyao
songyuanyao

Reputation: 172934

std::unique_ptr can't be copied, but moved, because it's unique. You could use std::move.

The class (std::unique_ptr) satisfies the requirements of MoveConstructible and MoveAssignable, but not the requirements of either CopyConstructible or CopyAssignable.

std::move is used to indicate that an object t may be "moved from", i.e. allowing the efficient transfer of resources from t to another object.

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

BTW: As @M.M mentioned, using std::unique_ptr::reset could solve your problem too, and more clear by avoiding all the temporary variables.

m_collection[0].reset(CreateNewMedia(Media info stuff)); 

Upvotes: 3

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.

Upvotes: 3

Kyle Knoepfel
Kyle Knoepfel

Reputation: 1698

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);

Upvotes: 3

Related Questions