C++核心准则C.40:如果类包含不变式,则定义构造函数

C.40: Define a constructor if a class has an invariant

C.40:如果类包含不变式,则定义构造函数

 

Reason(原因)

That's what constructors are for.

这就是构造函数存在的目的。

Example(示例)

扫描二维码关注公众号,回复: 9934388 查看本文章
class Date {  // a Date represents a valid date
              // in the January 1, 1900 to December 31, 2100 range
    Date(int dd, int mm, int yy)
        :d{dd}, m{mm}, y{yy}
    {
        if (!is_valid(d, m, y)) throw Bad_date{};  // enforce invariant
    }
    // ...
private:
    int d, m, y;
};

It is often a good idea to express the invariant as an Ensures on the constructor.

在构造函数中通过Ensure表现不变式通常都是一个好主意。

Note(注意)

A constructor can be used for convenience even if a class does not have an invariant. For example:

为了方便起见,即使类不包含不变式也可以为类定义构造函数。

struct Rec {
    string s;
    int i {0};
    Rec(const string& ss) : s{ss} {}
    Rec(int ii) :i{ii} {}
};

Rec r1 {7};
Rec r2 {"Foo bar"};

Note(注意)

The C++11 initializer list rule eliminates the need for many constructors. For example:

C++11的初始化列表消除了很多构造函数存在的必要性。例如:

struct Rec2{
    string s;
    int i;
    Rec2(const string& ss, int ii = 0) :s{ss}, i{ii} {}   // redundant
};

Rec2 r1 {"Foo", 7};
Rec2 r2 {"Bar"};

The Rec2 constructor is redundant. Also, the default for int would be better done as a member initializer.

Rec2的构造函数是多余的。同时成员初始化器提供的int的默认值会做得更好。

See also: construct valid object and constructor throws.

参见:【构建合法对象】和【构造函数抛出异常】

相关链接

成员初始化器:

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rc-in-class-initializer

构建合法对象:

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rc-complete

构造函数抛出异常:

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rc-throw

Enforcement(实施建议)

  • Flag classes with user-defined copy operations but no constructor (a user-defined copy is a good indicator that the class has an invariant)

  • 如果类包含用户定义的拷贝操作但是没有提供构造函数(用户定义的拷贝是类具有不变式的明显标志)

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c40-define-a-constructor-if-a-class-has-an-invariant


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

阅读更多更新文章,请关注微信公众号【面向对象思考】

发布了408 篇原创文章 · 获赞 653 · 访问量 29万+

猜你喜欢

转载自blog.csdn.net/craftsman1970/article/details/104396974
今日推荐