C ++中的值语义和移动语义之间有什么联系? [英] What's the connection between value semantics and move semantics in C++?

查看:90
本文介绍了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?

注意:这个问题不是关于比较值语义和移动语义的,因为很显然这两个概念不是可比较的".这个问题是关于它们如何连接的,特别是(如@StoryTeller所说的)是关于(如何)讨论的:

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.

推荐答案

来自

复制与移动

C和C ++建立在复制语义上.这是一件好事.移动 语义不是企图取代复制语义,也不是破坏 它以任何方式.相反,该建议旨在增强复制语义.一种 一般用户定义的类可能是可复制的又是可移动的,一个或 另一个,或者都不是.

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.

对于POD,移动和复制是相同的操作(一直到 机器指令级别).

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.

这篇关于C ++中的值语义和移动语义之间有什么联系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆