C ++ Move Semantics

I have this example:

Widget* makeWidget(int a, int b) {
if (a > b) {
    return new Widget(a);   
}
else {
    return new  Widget(b);  
 }
}

      

Isn't it like moving the return values, because you are just passing in a reference, not a copy? Why am I quitting Moving Constructor / Assignemnt?

Hello

+3


source to share


2 answers


Why would I graduate from Moving Constructor / Assignemnt?

In your function:

Widget* makeWidget(int a, int b);

      

You return Widget *

(i.e.: a pointer to Widget

), there is no object movement at all.




Isn't it like moving the return values, because you are just passing in a reference, not a copy?

It's not the same in terms of semantics, because when you move, you always return an object.

By moving, you are not actually copying, but moving data from the move object (i.e., the moved object) to the transition object (i.e., the object that is created or assigned through the move constructor or move assignment operator, respectively).

+1


source


Depending on what you are comparing to. If you've changed the return type to unique_ptr<Widget>

, you must use the move constructor to get clear property semantics.

Compared to normal return Widget

, if you did, you would also achieve non-nullability.



In your case, no action is taken, but you also have no advantage. You are returning what might be null, with no property specification. Without a move constructor, you can either do this or be copied to maintain correct semantics and guarantees. Moving constructors allows you to have that cake and eat it too.

+1


source







All Articles