前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则C.64:移动操作在完成移动之后,移动源对象应该保持有效状态

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

作者头像
面向对象思考
发布2020-03-25 16:16:07
3450
发布2020-03-25 16:16:07
举报

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(示例)

template<typename T>
class X {   // OK: value semantics
public:
    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


觉得本文有帮助?请分享给更多人。

关注【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-01-12,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c64-a-move-operation-should-move-and-leave-its-source-in-a-valid-state
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档