[英]std::move and map assignment
关于标准如何管理这种情况,我有点困惑:
struct Foo {
Foo & operator = (std::string xxx)
{
x = std::move(xxx);
return *this;
}
std::string x;
};
std::map<std::string, Foo> bar;
std::string baz = "some string";
bar[baz] = std::move(baz);
编译器是否可以生成代码,以便baz
在用于初始化之前移动并获取对bar
元素的引用(初始化std::string xxx
)? 或者这段代码是否安全且没有未定义的行为 ?
一定不行。 表达式是,等同于
(bar.operator[](baz)).operator=(std::move(baz))
但是(bar.operator[](baz)).operator=
的评估之间没有保证顺序(bar.operator[](baz)).operator=
- 形式上, postfix-expression指定要调用的函数 - 以及对operator=
的参数初始化的评估,这是从baz
移动的。
事实上, 这在GCC上断言 :
std::map<std::string, Foo> bar;
std::string baz = "some string";
bar[baz] = std::move(baz);
assert(bar.count("some string"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.