C.64: A move operation should move and leave its source in a valid state
C.64:移动操作在完成移动之后,移动源对象应该保持有效状态
Reason(原因)
That is the generally assumed semantics. After y = std::move(x) the value of y should be the value x had and x should be in a valid state.
这是普遍假定的语义。当y=std::move(x)被执行之后,y的值应该变为x,而x应该处于有效状态。
译者注:x的值被移除和状态无效不是一回事。
Example(示例)
templateclass X { // OK: value semanticspublic: X(); X(X&& a) noexcept; // move X void modify(); // change the value of X // ... ~X() { delete[] p; }private: T* p; int sz;};X::X(X&& a) :p{a.p}, sz{a.sz} // steal representation{ a.p = nullptr; // set to "empty" a.sz = 0;}void use(){ X x{}; // ... X y = std::move(x); x = X{}; // OK} // OK: x can be destroyed
Note(注意)
Ideally, that moved-from should be the default value of the type. Ensure that unless there is an exceptionally good reason not to. However, not all types have a default value and for some types establishing the default value can be expensive. The standard requires only that the moved-from object can be destroyed. Often, we can easily and cheaply do better: The standard library assumes that it is possible to assign to a moved-from object. Always leave the moved-from object in some (necessarily specified) valid state.
理想情况下,移动源对象应该变为默认值。除非有非常好的理由,否则一定要这么做。然而,并不是所有的类型都有默认值,有些类型构建有效状态的代码很高昂。标准的要求只是该对象可以被销毁。通常,我们可以以很小的代价很容易的做得更好:标准库的假设是可以为移动源对象赋值。保证移动后的移动源对象处于某种(不可避免地定义了的)有效状态。
Note(注意)
Unless there is an exceptionally strong reason not to, make x = std::move(y); y = z; work with the conventional semantics.
除非有特别强烈的理由不那么做,否则一定要保证在x=std::move(y)执行之后y=z可以按照通常的语义执行。
Enforcement(实施建议)
(Not enforceable) Look for assignments to members in the move operation. If there is a default constructor, compare those assignments to the initializations in the default constructor.
(不可执行)找到移动操作中的成员被赋值的情况。如果存在默认构造函数,比较移动操作中的赋值操作和默认构造函数中的赋值操作。
原文链接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c64-a-move-operation-should-move-and-leave-its-source-in-a-valid-state
觉得本文有帮助?请分享给更多人。
更多精彩文章请关注微信公众号【面向对象思考】!
面向对象开发,面向对象思考!