C.51: Use delegating constructors to represent common actions for all constructors of a class
C.51:使用委托构造函数实现所有构造函数的共通动作
委托构造函数是C++11引入的新特性,具体请参照作者的以下文章:
https://mp.weixin.qq.com/s/sHyLCI1tkLWvxfBKUiKwMg
Reason(原因)
To avoid repetition and accidental differences.
避免重复和意外的差异。
Example, bad(反面示例)
class Date { // BAD: repetitive
int d;
Month m;
int y;
public:
Date(int dd, Month mm, year yy)
:d{dd}, m{mm}, y{yy}
{ if (!valid(d, m, y)) throw Bad_date{}; }
Date(int dd, Month mm)
:d{dd}, m{mm} y{current_year()}
{ if (!valid(d, m, y)) throw Bad_date{}; }
// ...
};
The common action gets tedious to write and may accidentally not be common.
共通的动作写起来很乏味,偶尔也会变得不普通。
Example(示例)
class Date2 {
int d;
Month m;
int y;
public:
Date2(int dd, Month mm, year yy)
:d{dd}, m{mm}, y{yy}
{ if (!valid(d, m, y)) throw Bad_date{}; }
Date2(int dd, Month mm)
:Date2{dd, mm, current_year()} {}
// ...
};
See also: If the "repeated action" is a simple initialization, consider an in-class member initializer.
参考:如果“重复的动作”只是简单的初始化,考虑类内成员初始化器。
Enforcement(实施建议)
(Moderate) Look for similar constructor bodies.
(中等)寻找函数体相似的构造函数。
原文链接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c51-use-delegating-constructors-to-represent-common-actions-for-all-constructors-of-a-class
觉得本文有帮助?欢迎点赞并分享给更多的人。
阅读更多更新文章,请关注微信公众号【面向对象思考】