1

I am trying to add unique pointer to map.

auto monkey= std::unique_ptr<Animal> (new Animal(1,"Tom"));

std::map<int, std::unique_ptr<const Animal>> animals;    //Map of animals

animals.insert(pair<int, unique_ptr<Animal>>(1,monkey));    // Error here


Error:error: no matching function for call to 'std::pair<int, std::unique_ptr<Animal> >::pair(int&, std::unique_ptr<Animal>&)'

what would be the way to add it ??

3
  • Try this myMap.insert(std::make_pair(0, std::unique_ptr<Class1>(new Class1()))); on your example Commented Jan 10, 2020 at 10:41
  • 1
    animals.insert(pair<int, unique_ptr<Animal>>(1,std::move(monkey))); unique_ptr can be only moved, not copied. Commented Jan 10, 2020 at 10:41
  • Okay it seems to be working. Thanks. Commented Jan 10, 2020 at 10:43

2 Answers 2

5

std::unique_ptr is not copiable, but movable, you have to std::move it.

You might do:

animals.emplace(1, std::move(monkey));
Sign up to request clarification or add additional context in comments.

Comments

2

I would suggest you using the following when trying to insert std::unique_ptr into the std::map:

animals.insert(std::make_pair(1, std::unique_ptr<Animal>(new Animal(1,"Tom"))));

or

animals.insert(std::make_pair(1, std::make_unique<Animal>(1,"Tom")));

First, prefer using std::make_pair over std::pair constructor because with std::pair you need to specify the types of both elements, whereas std::make_pair will deduce the types of the elements that are passed to it.

Second, as the other answer says, std::unique_ptr can't be copied because it is unique. It can only be moved by std::move. In this case, since you are passing an r-value reference to the std::make_pair function it is being moved.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.