54

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?

Community
  • 1
  • 1
M3taSpl0it
  • 2,967
  • 6
  • 28
  • 27

1 Answers1

58

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.

fredoverflow
  • 256,549
  • 94
  • 388
  • 662
  • Can you explain when should be rvalue reference should be used? –  Jul 10 '11 at 19:22
  • @M3taSpl0it: Move constructors and move assignment operators have rvalue reference parameters. Apart from that, there's little use for them. Most of the time, they are buried deep inside library code, and your own code need not bother with rvalue references. – fredoverflow Jul 10 '11 at 21:28
  • You're missing a fundamentally important example. A function that returns a cv-qualified reference: `std::string const& reference_of_name() const`. This would be a prvalue, right? – void.pointer Jul 28 '15 at 19:37
  • cppreference article describes that lvalues are non-temporaries, and prvalues are temporary. Can you emphasize on this? – void.pointer Aug 11 '15 at 20:40