C ++标准是否保证插入关联容器失败不会修改rvalue-reference参数? [英] Does the C++ standard guarantee that a failed insertion into an associative container will not modify the rvalue-reference argument?

查看:87
本文介绍了C ++标准是否保证插入关联容器失败不会修改rvalue-reference参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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, unlike emplace, which requires the arguments to construct a value_type (that is, a std::pair)

这篇关于C ++标准是否保证插入关联容器失败不会修改rvalue-reference参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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