How to uniform initialize map of unique_ptr?

白昼怎懂夜的黑 提交于 2019-11-29 13:49:54

unique_ptr is movable, but not copyable. initializer_list requires copyable types; you can't move something out of an initializer_list. Unfortunately, I believe what you want to do isn't possible.

Incidentally, it would be more helpful to know which specific error you got. Otherwise, we have to guess whether you did something wrong and what, or whether what you want to do isn't implemented in your compiler, or is simply not supported in the language. (This is most helpful along with minimal reproduction code.)

As a workaround and especially when you want to have a const map containing unique_ptr, you can use a lambda executed in place. It is not an initializer list, but the result is similar:

typedef std::map<uint32_t, std::unique_ptr<int>> MapType;
auto const mapInstance([]()
{
   MapType m;
   m.insert(MapType::value_type(0x0023, std::make_unique<int>(23)));
   return m;
}());

or even simpler without typedef using make_pair:

auto const mapInstance([]()
{
   std::map<uint32_t, std::unique_ptr<int>> m;
   m.insert(std::make_pair(0x0023, std::make_unique<int>(23)));
   return m;
}());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!