我应该将临时移动到变量中吗?

Cof*_*ode 2 c++ move-semantics c++11 c++14

如果我有一个现有的非平凡变量,并且我想用新的内容重新分配它,我将在与赋值相同的行上声明,我应该使用移动语义吗?

我的问题来自以下场景:

std::vector<string> existing = { ... };

int main(int argc, char *argv[]){
    const char *bunch_of_strings = ... ;
    std::stringstream ss(bunch_of_string);

    existing = std::move(std::vector<std::string>(std::istream_iterator<std::string>(ss), {}));
}
Run Code Online (Sandbox Code Playgroud)

我应该这样做,如果我没有,编译器是否会同样优化它,或者它最好不要?

Pot*_*ter 9

std::move在那里是多余的.目的move是将变量视为临时变量(更确切地说,是右值),当它不是(或可能不是)时.如果它已经是右值,那么无论如何它肯定会被移动.