Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to emplace derived object into map

Tags:

c++

c++11

I'm still new to C++ and have come across a problem where I can't seem to insert a new derived class to a map.

My code is simplified as follows:

std::map<int, std::unique_ptr<Base_Class> > m;

void func(){
  for(int num = 0; num < 100; n++){
    m.emplace(num, new Derived_Class() );
  }  

}

Which gives me this:

error: no matching function for call to 'std::pair <const int, std::unique_ptr<Base_Class> >::pair(int&, Derived_Class*)

I've tried unsuccessfully using:

m.emplace(std::pair(num, new Derived_Class()) );

And which gives me this:

error: no matching function for call to 'std::pair<const int, std::unique_ptr<Base_Class> >::pair(std::pair<int, Derived_Class*>)

I can't seem to figure this one out and would appreciate any help.

like image 476
dyrandal Avatar asked Dec 09 '18 05:12

dyrandal


1 Answers

m.emplace(num, std::unique_ptr<Derived_Class>(new Derived_Class()));

Would be the way to go. Since the unique_ptr constructor taking a raw pointer is explicit, it cannot be implicitly initialized from a Derived_Class*. You need to explicitly create a unique_ptr object to emplace.

I posed this solution because you mentioned c++11, but the truly favorable way would be to use std::make_unique<Derived_Class>() (c++14 and onward), both to avoid repeating yourself, and to make the creation of the unique_ptr "atomic".

like image 176
StoryTeller - Unslander Monica Avatar answered Oct 02 '22 23:10

StoryTeller - Unslander Monica