Consider the following code:
class Widget {
public:
Widget() {
std::cout << "nCtor";
}
Widget(const Widget& obj) {
std::cout << "nCopy ctor";
}
Widget(Widget&& obj) noexcept {
std::cout << "nMove Ctor";
}
};
Widget foo(Widget obj) {
return obj;
}
And the caller side:
foo(std::move(w));
In this case we will have
Ctor
Move Ctor
Move Ctor
Even though we receive obj
in foo
by value, the move constructor will be called due to the std::move
. The second call of the move constructor will be done by the compiler as an optimization (is that correct?)
However, if we will change foo
to the
Widget foo(Widget&& obj) {
return obj;
}
the output will be
Ctor
Copy ctor
So my question is: why is it called copy constructor instead of the move constructor in the return statement, as before? We can only force the move constructor to be called by return std::move(obj)
exect is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3