Search code examples
c++value-categories

How to define xvalue mixed category?


Are all xvalues glvalues and rvalues at the same time? Or a xvalue may be either glvalue or a rvalue?

If it's a glvalue or/xor rvalue, can you give a example for each case?


Solution

  • From cppreference:

    An rvalue expression is either prvalue or xvalue.

    an xvalue (an “eXpiring” value) is a glvalue that denotes an object or bit-field whose resources can be reused;

    Answering your questions:

    Are all xvalues glvalues and rvalues at the same time?

    Yes. More specifically, rvalue is a superset of prvalue and xvalue. Thus all xvalues are rvalues, but not all rvalues are xvalues (namely, the ones that are prvalues). And by the definition above, xvalue is a reusable glvalue. So xvalues are both glvalues and rvalues.

    Or a xvalue may be either glvalue or a rvalue?

    No. xvalue is purely a reusable glvalue, and reusable glvalues (i.e. xvalues) are rvalues. Think move semantics.

    Examples:

    int a = 6;
    foo(6); // 6 is a prvalue (and thus is an rvalue)
    foo(a); // a is a glvalue
    
    std::vector<int> vec = {1, 2, 3};
    bar(vec);            // vec is a glvalue
    bar(std::move(vec)); // std::move(vec) is an xvalue (reusable glvalue)
                         // (and thus is an rvalue)