在C ++ 1z中是否有任何理由使用std :: map :: emplace()而不是try_emplace()? [英] Is there any reason to use std::map::emplace() instead of try_emplace() in C++1z?

查看:611
本文介绍了在C ++ 1z中是否有任何理由使用std :: map :: emplace()而不是try_emplace()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++ 17中, std :: map std :: unordered_map 获得了一个新的成员函数模板: try_emplace() 。在 n4279 中提出的新添加项,其行为类似于 emplace() ,但具有以下优点:

In C++17, std::map and std::unordered_map got a new member-function template: try_emplace(). This new addition, proposed in n4279, behaves similarly to emplace(), but has the following advantages:


  • try_emplace()如果不发生插入,则不会从右值参数移开。当操作其值为仅移动类型的地图时,例如 std :: unique_ptr

  • try_emplace()对待键和参数分别添加到 mapped_type ,这使其比以 value_type 表示的通用变量更直观。 std :: pair )。

  • try_emplace() does not move from rvalue arguments if the insertion does not happen. This is useful when manipulating maps whose values are move-only types, such as std::unique_ptr.
  • try_emplace() treats the key and the arguments to the mapped_type separately, which makes it somewhat more intuitive than generic mutators that are expressed in terms of value_type (which is std::pair).

鉴于上述优势,您是否会使用 emplace()编写纯C ++ 1z的代码时,使用C ++ 11z中的 try_emplace()来代替?

Given the above advantages, would you ever use emplace() from C++11 instead of try_emplace() from C++1z when writing C++1z-only code?

推荐答案

try_emplace 确实可以代替 emplace 的大多数用法,但是如果您有一个 map 的不寻常用例,它的键类型不可复制且不可移动,因此 try_emplace 不起作用,因为它复制或移动密钥。在这种情况下,必须将 emplace std :: pair 分段构造构造器,以避免复制和移动。

try_emplace can indeed replace most uses of emplace, but if you have an unusual use case of a map with a non-copyable and immovable key type, try_emplace will not work because it copies or moves the key. In that case, you must use emplace with std::pair's piecewise construction constructor to avoid copies and moves.

即使您的密钥类型是可复制和/或可移动的,分段构造是避免复制或移动构造键的唯一方法,因此在某些情况下,您可能更喜欢 try_emplace

Even if your key type is copyable and/or moveable, piecewise construction is the only way to avoid copy or move constructing the key, so there might be cases when you prefer that over try_emplace.

这篇关于在C ++ 1z中是否有任何理由使用std :: map :: emplace()而不是try_emplace()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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