Martin
Martin

Reputation: 923

Are there more than two benefits of move semantics?

I'm trying to more fully understand when to implement move semantics, and I believe it's intertwined with what the benefits are.

So far I'm aware of two.

  1. Saving two likely expensive operations when moving an object (copying when the source is known to vanish soon and not be used), without move a a full copy and a full destructor would have been executed, move will save an atomic increment and decrement for atomically reference counted objects, the deep copy of bitmaps or other data structures held by pointers, or a duplication of a file handle, one of which would be closed, or any other pair of "copy" and "destruct"

  2. Implement objects that can't be copied (as in duplicated), but can be moved, making sure there's ever only a single object with the same contents, yet the object can be handed off to a function. E.g. unique_ptr, or any object where copying is not possible or desired, but it needs to be created in one place but used somewhere else.

The distinction between the two is that the first deals with performance and the second with preventing semantic copying.

My question is this, are there any other uses or advantages to implementing move semantics for a class? A consideration other than performance or making sure only one location contains a live copy of the object.

Upvotes: 3

Views: 928

Answers (2)

Chris Drew
Chris Drew

Reputation: 15334

It is related to your points, but I think another benefit of move semantics is as a way of documenting ownership in your code. By using move you can make it clear that ownership of an object has been transferred from one place to another. This makes it easier to reason about code.

If you are trying to debug a program and understand the lifetime of an object, it is easier if there is just one path to follow. If ownership transfer is implemented as a copy you have to make sure that the lifetime of the original copy of the object has ended as well.

Upvotes: 0

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275310

When you move a container in certain contexts, the pointers and references and iterators travel with it. When you copy it, they do not. This is neither performance, nor an unmovable object; rather, move offers a different set of guarantees than copy.

This also can hold whenever you can have anything reference-like that talks about the "inside" of a complex object. move logically can make that reference travel, while copy may not.

Upvotes: 2

Related Questions