unique_ptr&lt;map&lt;int, unique_ptr&lt;Value&gt;&gt;&gt;对比 unique_ptr<map<int, Value>> [英] unique_ptr&lt;map&lt;int, unique_ptr&lt;Value&gt;&gt;&gt; vs. unique_ptr&lt;map&lt;int, Value&gt;&gt;

查看:43
本文介绍了unique_ptr&lt;map&lt;int, unique_ptr&lt;Value&gt;&gt;&gt;对比 unique_ptr<map<int, Value>>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正在修复 unique_ptr,我需要将 map 的 unique_ptr 作为参数传递给某个函数.

Working on a unique_ptr fix where I need to pass a unique_ptr of map to some function as argument.

如果我们通过std::make_unique定义map的unique_ptr,是否还需要将map的Value声明为unique_ptr 还要打字吗?

If we define a unique_ptr of map through std::make_unique, do we also need to declare the Value of the map as a unique_ptr type also?

或者我们不需要这样做,只要我们在堆中定义一个map的unique_ptr,然后我们就可以通过堆栈变量填充map值,map可以保存副本这些堆栈变量在其整个生命周期中都在堆中,直到所有者销毁此映射?

Or we don't need to do that, as long as we define a unique_ptr of map in the heap, then we can populate the map values through stack variable and the map can hold the copies of these stack variables throughout all its lifetime in heap until the owner destroy this map?

像这样:

auto heap_map = std::make_unique<std::map<
  int,
  std::unique_ptr<Value>>>();
    
(*heap_map)[1] = Value(arg1, arg2);
(*heap_map)[2] = Value(arg1, arg3);

或者我们必须这样做:

auto heap_map = std::make_unique<std::map<
  int,
  std::unique_ptr<Value>>>();

(*heap_map)[1] = std::make_unique<Value>(arg1, arg2);
(*heap_map)[2] = std::make_unique<Value>(arg1, arg3);

请说明上述两个用例之间的区别.

Please shed some light regarding the difference between these two use cases above.

推荐答案

无论您有地图,还是地图的 std::unique_ptr.这里真正的问题是如何填充地图中的 unique_ptr 条目.

Regardless of whether you have a map, or a std::unique_ptr to a map. The real issue here is how to fill the unique_ptr entries in the map.

// create the unique_ptr
auto ptr = std::make_unique<Value>(arg1,arg2);

// use the insert function instead of[]
// and unique pointers need to be moved (which will reset ptr)
// so do not use that after this call
heap_map->insert({0,std::move(ptr)});

这篇关于unique_ptr&lt;map&lt;int, unique_ptr&lt;Value&gt;&gt;&gt;对比 unique_ptr<map<int, Value>>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆