Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move semantics when sending object as function's parameter

I'm playing with move constructors and move assignments and i've stumbled on this problem. First code:

#include <iostream>
#include <utility>

class Foo {
    public:
        Foo() {}

        Foo(Foo&& other) {
            value = std::move(other.value);
            other.value = 1; //since it's int!
        }

        int value;

    private:
        Foo(const Foo& other);
};


void Bar(Foo&& x) {
    std::cout << "# " << x.value << std::endl;
}

int main() {
    Foo foo;
    foo.value = 5;

    Bar(std::move(foo));
    std::cout << foo.value << std::endl;

    return 0;
}

To my mind, when i use:

Bar(std::move(foo));

Program should "move" foo object to temp object created using move constructor in Bar function. Doing so would leave foo object's value equal zero. Unfortunatly it seams that object held in Bar function as parameter is some sort of reference, since it doesnt "move" original value but using Bar's parameter i can change it.

Would someone mind expalining me why i see in console:

#5
5

instead of

#5
0 //this should be done by move constructor?
like image 440
RippeR Avatar asked Nov 26 '14 00:11

RippeR


1 Answers

Bar function should not take reference && (this syntax is valid only in move constructor declaration/definition):

void Bar(Foo x) { ... }  // not "Foo&& x"

To call move constructor of temporary argument object in function Bar:

Bar(  std::move( x )  );

To call copy constructor:

Bar( x );
like image 175
fider Avatar answered Oct 18 '22 01:10

fider