Are move semantics useful if no heap is used?

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?

EDIT: yup my logic is flawed. move semantics are useful to implement things that cannot be duplicated by design (ex. a mutex lock), not just as an optimization

>Solution :

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.

Leave a Reply