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:
Stack<T>&&
be passed to a
different type Stack<int> second_a
? How does it work? Is there a implicit conversion?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;