Warm tip: This article is reproduced from stackoverflow.com, please click
c++ design-patterns pointers reference move

Why is it possible to assign a temporary value to a reference by passing it via the constructor?

发布于 2020-04-13 09:27:23
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 ?

Questioner
genaray
Viewed
63
Nicol Bolas 2020-02-03 03:33

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.