c++value-categories

C++ return by rvalue reference


template<typename T>
class Stack {
    private:
        std::vector<T> elems;  
    public:
        Stack () = default;
        Stack (T const& elem)
          : elems({elem}) {}
};

template<typename T>
Stack<T>&& dummy(Stack<T>&& a){
    return std::move(a);
}

int main(){
    Stack<int> first_a = 10;
    Stack<int> second_a = dummy(std::move(first_a));
    ...
}

The dummy function has a right value reference return type Stack<T>&&. However second_a has a Stack<int> type. My questions follow:


Solution

  • How does it work?

    second_a is copy initialised from the return value.

    Is there a implicit conversion?

    Yes. The rvalue reference to non-const is implicity converted into the lvalue reference to const that is the parameter of the copy constructor.

    dummy is quite pointless function. It's just std::move that can be called only on a Stack. std::move itself is also a function that returns an rvalue reference. The following is effectively the same:

    Stack<int> second_a = std::move(first_a);
    

    And since the class template doesn't have a move constructor, it's effectively same as:

    Stack<int> second_a = first_a;