Reputation: 309
I have this example:
Widget* makeWidget(int a, int b) {
if (a > b) {
return new Widget(a);
}
else {
return new Widget(b);
}
}
Isn't that the same like Moving the return values, because you just pass the reference and not a copy? Why do I end Moving Constructor/Assignemnt ?
Greetings
Upvotes: 3
Views: 226
Reputation: 24788
Why do I end Moving Constructor/Assignemnt ?
In your function:
Widget* makeWidget(int a, int b);
You are returning a Widget *
(i.e.: a pointer to Widget
) no move of an object takes place here at all.
Isn't that the same like Moving the return values, because you just pass the reference and not a copy?
It is not the same in terms of semantics, because by moving you always return an object.
By moving you are actually not copying, but moving the data from the move-from object (i.e.: the object being moved) to the move-to object (i.e.: the object being constructed or assigned to by means of the move constructor or move assignment operator, respectively).
Upvotes: 1
Reputation: 39390
Depends on what you compare it with. If you've replaced the return type with unique_ptr<Widget>
, you'd use the move constructor to achieve clear ownership semantics.
Compared to plain Widget
return, if you did that you'd also achieve non-nullability.
In your case no move is performed, but you also don't have any benefits. You return something that can be null with no ownership specification. Without a move constructor you can either do that, or be forced to copy to maintain proper semantics and guarantees. Move constructors allow you to have that cake and eat it, too.
Upvotes: 1