简体   繁体   English

std ::移动和地图分配

[英]std::move and map assignment

I am bit puzzled about how standard governs this case: 关于标准如何管理这种情况,我有点困惑:

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);

Can compilers produce code so that baz will be moved before it's used to initialise and get reference to element in bar (to initialise std::string xxx )? 编译器是否可以生成代码,以便baz 用于初始化之前移动并获取对bar元素的引用(初始化std::string xxx )? Or is this code safe and there's no undefined behaviour ? 或者这段代码是否安全且没有未定义的行为

Hell no. 一定不行。 The expression is, yes, equivalent to 表达式是,等同于

(bar.operator[](baz)).operator=(std::move(baz))

But there is no guaranteed order between the evaluation of (bar.operator[](baz)).operator= - formally, the postfix-expression designating the function to be called - and the evaluation of the initialization of the argument to operator= , which is what moves from baz . 但是(bar.operator[](baz)).operator=的评估之间没有保证顺序(bar.operator[](baz)).operator= - 形式上, postfix-expression指定要调用的函数 - 以及对operator=参数初始化的评估,这是从baz移动的。

In fact, this asserts on GCC : 事实上, 这在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM