c++c++11c++14xvalue

`xvalue` behavior in C++11/14


class Myclass
{    
public:
    Myclass() = default;
    ~Myclass() = default;
    Myclass(Myclass&&) = default;
    Myclass& operator=(Myclass&&) = default;

    Myclass(const Myclass&) = delete;

    Myclass& operator=(const Myclass&) = delete;
    int i = 0;
};

Myclass GetObj()
{
    Myclass obj;    
    return obj;
}

Myclass WrapperOfGetObj()
{
    Myclass&& Wrapobj = GetObj();
    Wrapobj.i = 1; // Will it work?

    return std::move(Wrapobj);
}

int main()
{
    return 0;
}

I have few questions: 1) In WrapperOfGetObj function, Wrapobj is xvalue, so can I assign value to any member of it (xvalue - going to expire!!)
2) What is the storage of xvalue? Is this not automatic storage?
3) When xvalue becomes glvalue and when it becomes rvalue.(Any example in above context will make this clear to me).


Solution

  • The expression Wrapobj is an lvalue. All named variables are lvalues.

    I think you are mixed up between the declared type of a variable, versus the type and value category of an expression consisting of the variable's name.

    decltype(Wrapobj) gives MyClass&&. When someone says "Wrapobj is an rvalue reference", they are talking about the declared type. But when Wrapobj is used in an expression, it has type MyClass and value category lvalue.

    There is no such thing as an expression with reference type. Also the type and value category of an expression is not directly related to whether the expression denotes a temporary object or not.

    For your question 2: "xvalue" is a value category of expressions. Expressions don't have storage. Objects have storage. References may or may not use storage (it is unspecified). Be sure to distinguish between storage of a reference, and storage of the object it refers to.

    The return value of GetObj() is a temporary object. The standard doesn't actually specify a storage duration for temporary objects, although common implementations use the stack (similar to automatic objects). I think C++17 may be improving the standard's wording in this area.