But why does C ++ not allow you to bind lvalue objects to rvalue values?
Assuming you mean "Why C ++ doesn't allow you to bind rvalue references to lvalue objects": this is so. It is simply not automatic, so you should use std::move
to make it explicit.
Why? Because otherwise, a harmless function call may unexpectedly destroy what you did not expect from it:
Class object(much,state,many,members,wow); looks_safe_to_me(object);
vs.
Class object(much,state,many,members,wow); obviously_destructive(std::move(object));
A note on destructive copying: why I say destructively and destruction above, I do not mean that the destructor object ends its life: its internal state simply moved to a new instance. It is still a valid object, but no longer contains the same expensive state in which it was used.
A note on terminology: see if we can eliminate the inaccurate use of lvalue, rvalue, etc. above.
Quote from cppreference for posterity:
So what actually happens:
- object exists
- the object is identified locally using the lvalue expression, which cannot be transferred from (to protect us from unexpected side effects)
std::move
gives an xvalue expression (which can be moved), referring to the same object as the lvalue expression- this means that objects, such as variables (called lvalue expressions), cannot be moved implicitly and must be moved explicitly from an explicit xvalue expression such as
std::move
. - anonymous temporary files are probably already mentioned by prvalue expressions and can be moved implicitly
source share