前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则C.40:如果类包含不变式,则定义构造函数

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

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

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

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

Reason(原因)

That's what constructors are for.

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

Example(示例)

代码语言:javascript
复制
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:

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

代码语言:javascript
复制
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的初始化列表消除了很多构造函数存在的必要性。例如:

代码语言:javascript
复制
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


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

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

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

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

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

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

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

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档