3

My intuition of move semantics is a shallow copy of an object's fields, followed by maybe some sabotaging of the old r-value. However, as far as I know there is only a difference in shallow/deep copies when some fields are owning pointers/references. If you weren't to use the heap at all, so no malloc or new, then you would probably have no classes/structs with owning pointers. Therefore, move constructors wouldn't have any difference between a regular copy constructors. Is my logic correct?

cigien
  • 57,834
  • 11
  • 73
  • 112
k huang
  • 409
  • 3
  • 10
  • 5
    I'd tend to agree, but don't forget objects that do not allocate heap yet represent move-only resources (network sockets, files, ...). – chi May 22 '23 at 22:21
  • 3
    You should stop thinking in terms of heap and stack which is an implementation detail, but of [lifetime](https://en.cppreference.com/w/cpp/language/lifetime) instead. In addition to that there are not only pointers/references that are part of resource acquiring that can also happen based on IDs (like if you request resources from a GPU), or even for resources that are not located on the machine the code is running on (networking). But in the end - besides optimization - it boils down to having member variables that (based on the code logic) are considered to be uniquely owned. – t.niese May 22 '23 at 22:45
  • @t.niese fair point, this was just coming from the context of no heap allowed for a real time system – k huang May 22 '23 at 22:47
  • 1
    I understand that. However adding the layer of implementation details to the thinking just makes things much more complicated. Because if you e.g. consider [placement new](https://stackoverflow.com/questions/222557) or [custom new](https://stackoverflow.com/questions/7194127), and only use memory on the stack in that case, then no heap is involved, but you still would use move semantics for the same reason as if it is allocated on the heap. – t.niese May 22 '23 at 22:55
  • Please don't edit the question to include an answer. If you have an answer that is not covered already you can post an answer yourself. – cigien May 23 '23 at 07:17

1 Answers1

7

Yes, it is useful for managing ownership of any kind of resource, not just heap memory.

For example a (open) std::ofstream represents ownership of an output stream to an open file. It doesn't make sense to be able to copy such a stream and therefore it is non-copyable. But it is still possible to transfer the ownership of the stream from one std::ofstream object to another via move construction/assignment.

user17732522
  • 53,019
  • 2
  • 56
  • 105