C ++标准是否保证插入关联容器失败不会修改rvalue-reference参数? [英] Does the C++ standard guarantee that a failed insertion into an associative container will not modify the rvalue-reference argument?
问题描述
#include <set>
#include <string>
#include <cassert>
using namespace std::literals;
int main()
{
auto coll = std::set{ "hello"s };
auto s = "hello"s;
coll.insert(std::move(s));
assert("hello"s == s); // Always OK?
}
C ++标准是否保证插入关联容器失败不会修改rvalue-reference参数?
推荐答案
明确且明确的否. Standard没有这种保证,这就是为什么 try_emplace 存在的原因.
Explicit and unequivocal NO. Standard doesn't have this guarantee, and this is why try_emplace exists.
请参阅注释:
与插入或换位不同,这些函数不会从右值移开 如果不插入该参数,则很容易 处理其值为仅移动类型的地图,例如
std::map<std::string, std::unique_ptr<foo>>
.另外,try_emplace
不同于对待映射类型的键和参数,emplace
,需要参数来构造value_type
( 是std::pair
)
Unlike insert or emplace, these functions do not move from rvalue arguments if the insertion does not happen, which makes it easy to manipulate maps whose values are move-only types, such as
std::map<std::string, std::unique_ptr<foo>>
. In addition,try_emplace
treats the key and the arguments to the mapped_type separately, unlikeemplace
, which requires the arguments to construct avalue_type
(that is, astd::pair
)
这篇关于C ++标准是否保证插入关联容器失败不会修改rvalue-reference参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!