So I've been burned by this a couple of times. What is the difference between this:
Movable&& object = std::move(another_movable);
and this:
Movable object = std::move(another_movable);
It seems like both should work equally, but I always get inexplicable behavior (properties of the object changing) with the second example. Why is this?
Maybe comparing it to an lvalue-reference version might help:
Object& object = another_object;
Object object = another_object;
The first is a reference to an lvalue, so no constructors are called. It just refers to the object named another_object
, like a pointer. Object object
creates a brand new object so the constructors will be called (not assuming copy-elision).
Now rvalue-references are the same, but they are tailored exclusively for rvalues. They now refer to the rvalue from which it is initialized.
Movable&& object = std::move(another_movable);
This makes another reference to the same object as another_movable
.
Movable object = std::move(another_movable);
This makes a new object initialized from an rvalue of another_movable
.
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