移动局部变量时我应该使用std :: move吗?

bal*_*lki 2 c++ c++11

考虑以下代码:

Bar my_f()
{
    Foo f{args,to,create,foo};
    Bar b{std::move(f),other,args}; //Is move here unnecessary?

    // code that does not use f;

    return b;
}
Run Code Online (Sandbox Code Playgroud)

是否需要编译器检查{code that does not use f}并自动f进入b

nos*_*sid 5

编译器不会自动将对象移动到构造函数中Bar,只是因为f之后没有使用它.如果要移动f,请使用std::move(f)或删除命名变量:

Bar b{Foo{args, to, create, foo}, other, args}; // will automatically move (if possible)
Run Code Online (Sandbox Code Playgroud)