如何将派生对象放置到地图中

时间:2018-12-09 05:43:03

标签: c++ c++11

我对C ++还是很陌生,遇到了一个问题,我似乎无法在地图上插入新的派生类。

我的代码简化如下:

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

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

}

哪个给我这个:

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

我尝试使用以下方法失败:

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

这给了我这个:

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

我似乎无法弄清楚这一点,将不胜感激。

1 个答案:

答案 0 :(得分:5)

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

将是要走的路。由于采用原始指针的unique_ptr构造函数是显式的,因此无法从Derived_Class*隐式初始化它。您需要显式创建一个unique_ptr对象以放置。

我提出此解决方案是因为您提到了,但真正的好方法是使用std::make_unique<Derived_Class>()及更高版本),既避免重复自己,又使创建“ atomic”的unique_ptr。