Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

where and when an xvalue is used?

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?

like image 653
Zachary Avatar asked Jun 30 '13 03:06

Zachary


1 Answers

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.

like image 90
jogojapan Avatar answered Oct 07 '22 10:10

jogojapan