gpt4 book ai didi

c++ - 我可以委托(delegate) Move Constructor 吗?

转载 作者:行者123 更新时间:2023-11-28 01:17:04 25 4
gpt4 key购买 nike

我在 Foo 类中定义了复制构造函数和移动构造函数。在调试过程中,我进入了 f = CreateFoo(1, 1); 并将我带到了 Foo(Foo&& other) : Foo(other, 0) {}。下一步将我带到 Foo(Foo& other, int m) :x(other.x + m), y(other.y - m) {},这是一个复制构造函数。我正在委托(delegate)一个移动构造函数,我期望它执行 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;
}

最佳答案

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

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

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

关于c++ - 我可以委托(delegate) Move Constructor 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58349802/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com