C++11 隐式移动构造函数

C++11 implicit move constructors

本文关键字:构造函数 移动 C++11      更新时间:2023-10-16

我很难理解为什么以下内容(至少根据 gcc 4.8)在 C++11 中是合法的:

// This class manages a non-copyable resource.
struct B {
  B();
  B(B &&) { /* logging, etc., to verify if needed. */ }
private:
  B(B const &);
  B const &operator=(B const &);
};
B bar() {
  B b;
  // This is apparently allowed via the move constructor.
  return b;
};
int main() {
  // From this "side" of the call as well.
  B b1 = bar();
  B b2{bar()};
}

在哪些上下文中,语言允许或实际首选移动构造函数?临时返回值似乎可以移动(和垃圾内容),但我想找到所有可以静默使用移动的地方的核心语言规则。谢谢!

每当参数绑定到rvalue引用时,编译器都可以使用移动。 每当参数为prvalue时,编译器都会使用它(见下文)。 参数也可以转换为rvalue引用。

通常,右值是出现在作业右侧的任何内容。 考虑它的一个粗略方法是是否可以在代码中引用它。 左值有身份,右值通常没有。

真的,有几种类型的左值和右值...

  • lvalue - 有身份,不能移动 ( lvalue
  • xvalue - 具有身份,可以移动(lvaluervalue
  • prvalue - 没有身份,可以移动 ( rvalue

xvalue既是lvalue,也是rvalue。 例如,您使用 std::move 显式强制转换为rvalue引用的内容。

此外,还有一个很好的介绍来重新定义引用和移动语义 http://www.cprogramming.com/c++11/rvalue-references-and-move-semantics-in-c++11.html