c++ - C++ 中的值语义和 move 语义之间有什么联系?

标签 c++ c++11 move-semantics

有很多文章讨论值语义与引用语义,也许更多的文章试图解释 move 语义。然而,从来没有人谈论过值语义和 move 语义之间的联系。它们是正交概念吗?

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

Move semantics help facilitate more use of value types.

最佳答案

来自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).

我想有人可以补充说:

move 语义允许我们保留值语义,但同时在原始(复制自)对象的值对程序逻辑不重要的情况下获得引用语义的性能。

关于c++ - C++ 中的值语义和 move 语义之间有什么联系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50198991/

相关文章:

c++ - 无法推断模板参数 - 泛型函数

C++ 当函数返回 vector<shared_ptr<>> 时会发生什么?

c++ - 命名嵌套类时无法在 Lambda 中解析名称

c++ - 将类成员绑定(bind)到普通 C 函数指针

c++ - SFINAE 无法有条件地编译成员函数模板

C++11/VS2010 : Returning containers of uncopyable but movable objects

c++ - 不要删除不是 owner<T> 的原始指针 (i.11)

C++ 集合 : how to create a map like structure

c++ - 将成员变量复制到字节 vector 中

c++ - 使用 strlen() 查找字符串数组的长度