class MoveSemantic{
public:
// For inserting a value
MoveSemantic(short &value);
MoveSemantic(short &&value);
short &storedValue;
};
// Reference forced to initialize
MoveSemantic::MoveSemantic(short &value) : storedValue(value) {}
MoveSemantic::MoveSemantic(short &&value) : storedValue(value) {}
// Passing a RValue => Assiging to reference => Is this safe ?
MoveSemantic semantik(100);
cout << semantik.storedValue; // 100
I lately discovered that its possible to assign a temporary value to a reference inside a class by abusing the rvalue semantics... But why is this possible ? How does the memory behaves ?
Does this extend the lifetime of the temporary variable "100" due to its assigning ? How safe is this ? And when does the temporary value gets destroyed by the scope ?
It is possible because C++ is not a safe language; it expects you to know what you're doing. If you take an rvalue reference parameter, it expects that you know what you're doing with it. If you store that as a reference member of an object, it expects that you will have ensured that the object being referenced will continue to exist for as long as that object needs it to.
And if you violate these expectations, you suffer the consequences.
An rvalue reference is not necessarily a "temporary object". It can be a reference to any object from which it is OK to move. This is why std::move
exits: to designate that it is OK to move from a non-temporary object by returning an rvalue reference to it.
Is
100
, there, really a temporary?@Jeffrey: It will provoke the creation of a temporary object.