Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Real life examples of xvalues, glvalues, and prvalues?

Tags:

c++

c++11

I was wondering if anyone could tell or explain some real life examples of xvalues, glvalues, and prvalues?. I have read a similar question :

What are rvalues, lvalues, xvalues, glvalues, and prvalues?

but I did not understand what everyone meant. Can anyone explain in what cases these values are important and when one should use them?

like image 584
M3taSpl0it Avatar asked Jul 07 '11 11:07

M3taSpl0it


People also ask

What is an Xvalue?

An xvalue (an “eXpiring” value) also refers to an object, usually near the end of its lifetime (so that its resources may be moved, for example). An xvalue is the result of certain kinds of expressions involving rvalue references.

What are Lvalues and Rvalues?

An lvalue (locator value) represents an object that occupies some identifiable location in memory (i.e. has an address). rvalues are defined by exclusion. Every expression is either an lvalue or an rvalue, so, an rvalue is an expression that does not represent an object occupying some identifiable location in memory.

What are Lvalues and Rvalues in C++?

Lvalues and rvalues are fundamental to C++ expressions. Put simply, an lvalue is an object reference and an rvalue is a value. The difference between lvalues and rvalues plays a role in the writing and understanding of expressions.


1 Answers

Consider the following class:

class Foo {     std::string name;  public:      Foo(std::string some_name) : name(std::move(some_name))     {     }      std::string& original_name()     {         return name;     }      std::string copy_of_name() const     {         return name;     } }; 

The expression some_foo.copy_of_name() is a prvalue, because copy_of_name returns an object (std::string), not a reference. Every prvalue is also an rvalue. (Rvalues are more general.)

The expression some_foo.original_name() is an lvalue, because original_name returns an lvalue reference (std::string&). Every lvalue is also a glvalue. (Glvalues are more general.)

The expression std::move(some_name) is an xvalue, because std::move returns an rvalue reference (std::string&&). Every xvalue is also both a glvalue and an rvalue.


Note that names for objects and references are always lvalues:

std::string a; std::string& b; std::string&& c; 

Given the above declarations, the expressions a, b and c are lvalues.

like image 84
fredoverflow Avatar answered Sep 23 '22 17:09

fredoverflow