3

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

JFMR
  • 23,265
  • 4
  • 52
  • 76
mcAngular2
  • 299
  • 1
  • 14
  • Why not this way: `Widget* makeWidget(int a, int b) { return new Widget(a > b ? a : b); }` In C++ the `?:` operator may even handle references. I.e. I 've used it even for conditional calls of constructors (themselves) for initialization of instances. – Scheff's Cat Jun 09 '17 at 09:54
  • 1
    @Scheff absolutely irrelevant to the question at hand. It's clearly just an example. – Bartek Banachewicz Jun 09 '17 at 09:54
  • @BartekBanachewicz If the questioner didn't consider that a (raw) pointer assignment doesn't mean any move semantics he might have missed other (even simpler) opportunities also... – Scheff's Cat Jun 09 '17 at 09:57
  • 1
    Also [relevant](https://stackoverflow.com/a/11540204/752976) – Bartek Banachewicz Jun 09 '17 at 09:58

2 Answers2

1

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).

JFMR
  • 23,265
  • 4
  • 52
  • 76
  • 1
    @GillBates A raw pointer cannot be moved (or more precisely, moving a raw pointer is no different to copying it). – Walter Jun 09 '17 at 10:16
  • @Walter mhmm, there's no benefit out of it but I just noted it to keep OP aware of semantics with return statements. You're right it has no use here though. – Hatted Rooster Jun 09 '17 at 10:30
1

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.

Bartek Banachewicz
  • 38,596
  • 7
  • 91
  • 135