【问题标题】:Can I delegate Move Constructor?我可以委托移动构造函数吗?
【发布时间】:2020-02-09 11:39:58
【问题描述】:

我在 Foo 类中定义了复制构造函数和移动构造函数。在调试过程中,我进入f = CreateFoo(1, 1);,它会将我带到Foo(Foo&& other) : Foo(other, 0) {}。下一步将我带到Foo(Foo& other, int m) :x(other.x + m), y(other.y - m) {},它是一个复制构造函数。我正在委派一个移动构造函数,我期待它执行Foo(Foo&& other, int m) : x(std::move(other.x)), y(std::move(other.y))。我不明白为什么?谁能给我一些帮助?以下是完整的程序。

class Foo
{
public:
    int x;
    int y;
public:
    Foo(int i, int j) : x(i), y(j) {}
    Foo(Foo& other) : x(other.x), y(other.y) {}
    Foo(Foo& other, int m) :x(other.x + m), y(other.y - m) {}
    Foo(Foo&& other, int m) : x(std::move(other.x)), y(std::move(other.y))
    {
        x = x + m;
        y = y - m;
    }
    Foo(Foo&& other) : Foo(other, 0) {}
    Foo& operator=(const Foo& other) {
        x = other.x;
        y = other.y;
        return *this;
    }

    Foo& operator=(Foo&& other)
    {
        x = std::move(other.x);
        y = std::move(other.y);
        return *this;
    }
};

Foo CreateFoo(int x, int y)
{
    Foo tmp(x, y);
    return tmp;
}

int main()
{
    Foo f(0, 0);
    f = CreateFoo(1, 1);
    system("pause");
    return 0;
}

【问题讨论】:

  • 你必须使用std::move(other)进行委托。
  • Foo(Foo&& other) 内部,other 是一个左值,因为它有一个名称,这就是Foo(Foo& other, int m) 被委派给它的原因。使用std::move(other) 进行右值引用,以便它可以委托给Foo(Foo&& other, int m)Foo(Foo&& other) : Foo(std::move(other), 0) {}
  • 重复谈论基本构造函数,但这里同样适用。
  • 顺便说一句。复制构造函数应该通过const 引用来获取它的参数。

标签: c++ constructor move-constructor


【解决方案1】:
Foo(Foo&& other) : Foo(other, 0) {}

这里other 是一个左值(它有一个名字!)。您需要再次使用 std::move 委托调用,使其成为 xvalue:

Foo(Foo&& other) : Foo(std::move(other), 0) {}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-31
    • 2015-02-10
    • 1970-01-01
    • 1970-01-01
    • 2012-11-15
    相关资源
    最近更新 更多