Question

I read the standard on xvalue. It is closely associated with rvalue reference expression. But when programming, I really cannot find scenarios that needs xvalue.

For example: function myClass&& f() return an rvalue reference. So expression f() is xvalue. But how is this useful? How can I make use of this technique in programming?

If another function myClass g() is defined, what is the difference between g() and f()?

Under what circumstances should I use f() and xvalue instead of g() prvalue?

Was it helpful?

Solution

In your example, you defined a function g which returns a prvalue, and a function f which returns an xvalue.

What these have in common is that if you pass the result of the function call, g() and f() respectively, to another function h(...), they will both prefer the overload of h that takes an rvalue as argument (if there are multiple overloads of h).

The difference between g() and f() is that g() has no dynamic type (i.e. the dynamic type is the same as the static (=declared) type), whereas f() has dynamic type (possibly different from the static type), in other words, if it's defined to return an rvalue reference to a base class, it will enable polymorphic behaviour. (It's this characteristic that xvalues share with lvalues, which is why xvalues and lvalues together form the larger group of glvalues, whereas prvalues are only rvalues.)

For examples of use cases, I'll just refer to this existing question: Is there any case where a return by rvalue reference is useful.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top