前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则E4,5:设计并构建不变量

C++核心准则E4,5:设计并构建不变量

作者头像
面向对象思考
发布2020-07-29 11:43:22
4820
发布2020-07-29 11:43:22
举报

E.4: Design your error-handling strategy around invariants

E.4:围绕不变量设计错误处理策略

Reason(原因)

To use an object it must be in a valid state (defined formally or informally by an invariant) and to recover from an error every object not destroyed must be in a valid state.

为了使用对象,它一定要处于有效状态(通过不变量形式化或非形式化定义)并且为了从错误中恢复,所有没有销毁的对象必须处于有效状态。

Note(注意)

An invariant is a logical condition for the members of an object that a constructor must establish for the public member functions to assume.

不变量是一个适用于对象成员的逻辑条件,这个条件必须有构造函数建立,可以作为公有成员函数的前提条件。

Enforcement(实施建议)

???

E.5: Let a constructor establish an invariant, and throw if it cannot

E.5:让构造函数建立不变量,如果不能就抛异常

Reason(原因)

Leaving an object without its invariant established is asking for trouble. Not all member functions can be called.

建立一个对象却没有建立不变量是在找麻烦。不是所有成员函数都是可以被调用的。

Example(示例)

代码语言:javascript
复制
class Vector {  // very simplified vector of doubles
    // if elem != nullptr then elem points to sz doubles
public:
    Vector() : elem{nullptr}, sz{0}{}
    Vector(int s) : elem{new double[s]}, sz{s} { /* initialize elements */ }
    ~Vector() { delete [] elem; }
    double& operator[](int s) { return elem[s]; }
    // ...
private:
    owner<double*> elem;
    int sz;
};

The class invariant - here stated as a comment - is established by the constructors. new throws if it cannot allocate the required memory. The operators, notably the subscript operator, relies on the invariant.

See also: If a constructor cannot construct a valid object, throw an exception

类不变量-这里通过注释声明-通过构造函数建立了。如果不能分配要求的内存,new操作会抛出异常。运算符,特别是下标运算符依靠不变量。参见:如果不能构建有效的对象,就抛出异常。

Enforcement(实施建议)

Flag classes with private state without a constructor (public, protected, or private).

标记那些没有构造函数(公有的,私有的或保护的)却有私有成员的类。

原文链接https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#e4-design-your-error-handling-strategy-around-invariants

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • E.4: Design your error-handling strategy around invariants
  • Reason(原因)
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档