0

There is great confusion surrounding move semantics in C++. I believe I understand, at a basic level, how you can use it to avoid copying data upon returning from a function, but couldn't this always be achieved by returning a reference instead?

Even when copying large data structures, aren't you usually copying a few small pointers to the large data, rather than copying the data itself?

Can you give an example of using move semantics to do something that you couldn't do by simply returning a reference? Or perhaps I'm misunderstanding and that this is mostly a nice-to-have syntactic sugar thing so that you don't have to think about references as much in user code?

JacKeown
  • 2,780
  • 7
  • 26
  • 34
  • 2
    Does this answer your question? [What is move semantics?](https://stackoverflow.com/questions/3106110/what-is-move-semantics) – Richard Critten Nov 09 '20 at 18:18
  • 2
    Return a reference to what? The things inside the function no longer exist when it returns. – GManNickG Nov 09 '20 at 18:18
  • 1
    [Watching this presentation will be an hour-and-a-bit of your life well spent.](https://www.youtube.com/watch?v=vLinb2fgkHk) – user4581301 Nov 09 '20 at 18:21
  • Before move semantic, to avoid extra copy, we used output parameter that we mutate, so `void init_Foo(Foo&)` instead of current `Foo make_Foo()`. – Jarod42 Nov 09 '20 at 18:21
  • See comments from GManNickG. You could (icky) return a reference to a static object (can I say Yuck a few times), but then the caller has a reference (which is just a shortcut for a pointer) to your static reference. And then he starts changing it -- changing ALL of the places, because they're all pointers. – Joseph Larson Nov 09 '20 at 18:37
  • @GManNickG I was thinking of returning a reference to something allocated on the heap. (Which would still exist after returning) – JacKeown Nov 09 '20 at 19:53
  • The post "What is move semantics" doesn't answer my question. I've seen move semantics used and understand what's happening, but not why the same behavior couldn't be implemented using pointers alone. – JacKeown Nov 09 '20 at 19:58
  • 1
    The beauty of move semantics is you won't have to manually allocate on the heap. Much lower memory management overhead (for both the computer and the programmer). – user4581301 Nov 09 '20 at 19:58

0 Answers0