【问题标题】:Should I use std::move when moving local variables? [duplicate]移动局部变量时应该使用 std::move 吗? [复制]
【发布时间】:2014-05-07 20:37:26
【问题描述】:

考虑下面的代码:

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

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

【问题讨论】:

  • 编译器不太可能移动f。只要遵循 as-if 规则,它可能会做一些更高效、更容易实现的事情。某处有重复。
  • 无法保证编译器会这样做......我怀疑编译器会自动这样做,因为它会破坏范围规则。

标签: c++ c++11


【解决方案1】:

编译器不会自动将对象移动到Bar的构造函数中,只是因为之后没有使用f。如果你想移动 f,要么用 std::move(f) 显式化它,要么移除命名变量:

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

【讨论】:

    猜你喜欢
    • 2013-08-16
    • 2013-02-06
    • 2018-01-22
    • 2015-06-04
    • 1970-01-01
    • 1970-01-01
    • 2013-08-06
    • 2012-06-12
    • 2019-07-14
    相关资源
    最近更新 更多