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:
- How can the return value of the dummy function, which has type
Stack<T>&&be passed to a different typeStack<int> second_a? How does it work? Is there a implicit conversion?
second_ais copy initialised from the return value.Yes. The rvalue reference to non-const is implicity converted into the lvalue reference to const that is the parameter of the copy constructor.
dummyis quite pointless function. It's juststd::movethat can be called only on aStack.std::moveitself is also a function that returns an rvalue reference. The following is effectively the same:And since the class template doesn't have a move constructor, it's effectively same as: