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


class Vector {  // very simplified vector of doubles    // if elem != nullptr then elem points to sz doublespublic:    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).

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

 


 


关注微信公众号【面向对象思考】轻松学习每一天!

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

 

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