【问题标题】:Why move constructor of member variable is not called?为什么不调用成员变量的移动构造函数?
【发布时间】:2020-10-14 07:09:34
【问题描述】:

考虑以下类。如果我自己实现移动构造函数如下,为什么 bar 成员 b 没有被移动而是被复制?但是如果我使用默认的移动构造函数,那么b 会被移动。为什么b(rhs.b) 不调用bar(bar&&)

我使用带有 --std=c++11 的 g++ 9.2.1。

class bar {
public:
    bar() { cout << "bar constructor" << endl; }
    bar(const bar& rhs) { cout << "bar copy constructor" << endl; }
    bar(bar&& rhs) { cout << "bar move constructor" << endl; }
};

class foo {
    bar b;
public:
    foo() { cout << "foo constructor" << endl; }
    foo(const foo& rhs) { cout << "foo copy constructor" << endl; }
    // foo(foo&& rhs) = default;
    foo(foo&& rhs) : b(rhs.b) { cout << "foo move constructor" << endl; } // my version
    //               ^^^^^^^^
};

foo f;
foo g = std::move(f);

【问题讨论】:

    标签: c++ c++11 rvalue lvalue move-constructor


    【解决方案1】:

    为什么b(rhs.b) 不调用bar(bar&amp;&amp;)

    因为rhs.b 是一个左值,并且右值引用不绑定到左值。结果——因为左值引用确实绑定到左值——重载bar(const bar&amp;),即复制构造函数,被选择而不是bar(bar&amp;&amp;).

    为了选择移动构造函数,您需要在初始化foob 成员时使用(&lt;utility&gt;std::move()rhs.b 标记为“可移动”:

    foo(foo&& rhs): b(std::move(rhs.b)) { /* ... */ }
                      ^^^^^^^^^
    

    这是一个将表达式rhs.b 转换为xvalue,即rvalue 的转换,它绑定到rvalue 引用 .所以,这次选择了移动构造函数。

    但是如果我使用默认的移动构造函数,那么b 会被移动。

    默认移动构造函数执行成员移动。

    【讨论】:

      猜你喜欢
      • 2011-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-01
      • 2017-01-10
      • 2023-03-18
      • 1970-01-01
      相关资源
      最近更新 更多