Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading