inflator
inflator

Reputation: 39

Can I delegate Move Constructor?

I have copy constructors and move constructors defined in class Foo. In debugging I step in f = CreateFoo(1, 1); and it takes me to Foo(Foo&& other) : Foo(other, 0) {}. The next step-in takes me to Foo(Foo& other, int m) :x(other.x + m), y(other.y - m) {} which is a copy constructor. I am delegating a move constructor, I am expecting it executes Foo(Foo&& other, int m) : x(std::move(other.x)), y(std::move(other.y)). I don't understand why? Can anyone give me some help? Below is the full program.

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

Upvotes: 0

Views: 540

Answers (1)

ph3rin
ph3rin

Reputation: 4896

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

Here other is a lvalue (it has a name!). You need to delegate the call by using std::move again, to make it an xvalue:

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

Upvotes: 2

Related Questions