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?
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 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With