C++核心准则C.64:移动操作在完成移动之后,移动源对象应该保持有效状态

网友投稿 519 2022-09-06

C++核心准则C.64:移动操作在完成移动之后,移动源对象应该保持有效状态

C++核心准则C.64:移动操作在完成移动之后,移动源对象应该保持有效状态

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​​

觉得本文有帮助?欢迎点赞并分享给更多的人。

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:C++核心准则边译边学-X.5:尽量不使用类型转换
下一篇:SQLServer 2012之AlwaysOn —— 指定数据同步链路,消除网络抖动导致的提交延迟问题(sqlserver无法连接到服务器怎么办)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~