How to Store an lvalue or an rvalue in the Same Object

submited by
Style Pass
2022-05-20 20:30:05

There seems to be a problem coming up every so often C++ code: how can an object keep track of a value, given that this value can come from either an lvalue or an rvalue?

In short, if we keep the value as a reference then we can’t bind to temporary objects. And if we keep it as a value, we incur unnecessary copies when it is initialized from an lvalue.

There are several ways to cope with this situation. I find that using std::variant offers a good trade-off to have expressive code.

Consider a class MyClass. We would like to give MyClass access to a certain std::string. How do we represent the string inside of MyClass?

Then the code has undefined behaviour. Indeed, the temporary string object is destroyed on the same statement it is created. When we call print, the string has already been destroyed and using it is illegal and leads to undefined behaviour.

The other option we have is to store a value. This allows us to use move semantics to move the incoming temporary into the stored value:

Leave a Comment