Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the connection between value semantics and move semantics in C++?

There're plenty of articles discussing value semantics vs reference semantics, and maybe more trying to explain move semantics. However, No one has ever talked about the connection between value semantics and move semantics. Are they orthogonal concepts?

Note: This question is NOT about comparing value semantics vs move semantics, cause it is perfectly clear these two concepts are not "comparable". This question is about how they are connected, specifically (like @StoryTeller said), about discussing(how):

Move semantics help facilitate more use of value types.

like image 774
laike9m Avatar asked Sep 03 '25 03:09

laike9m


1 Answers

From the original move proposal:

Copy vs Move

C and C++ are built on copy semantics. This is a Good Thing. Move semantics is not an attempt to supplant copy semantics, nor undermine it in any way. Rather this proposal seeks to augment copy semantics. A general user defined class might be both copyable and movable, one or the other, or neither.

The difference between a copy and a move is that a copy leaves the source unchanged. A move on the other hand leaves the source in a state defined differently for each type. The state of the source may be unchanged, or it may be radically different. The only requirement is that the object remain in a self consistent state (all internal invariants are still intact). From a client code point of view, choosing move instead of copy means that you don't care what happens to the state of the source.

For PODs, move and copy are identical operations (right down to the machine instruction level).

I guess one could add to this and say:

Move semantics allows us to keep value semantics, but at the same time gain the performance of reference semantics in those cases where the value of the original (copied-from) object is unimportant to program logic.

like image 85
Howard Hinnant Avatar answered Sep 05 '25 21:09

Howard Hinnant