著者はBjarne Stroustrup氏とHerb Sutter氏
C++Core Guidelinesって?
「The C++ Core Guidelines are a set of tried-and-true
guidelines, rules, and best practices about coding in C++」
「C++コーディングにおける実証済みのガイドラインと
ルール、そしてベストプラクティスの集合体である」
21.
Q. C++ CoreGuidelinesは
"More" Effective Modern C++か?
メンバ変数のリスト初期化の例
class Bad {// メンバ変数をリスト初期化するべき
string s;
int i;
public:
X1() :s{"default"}, i{1} { }
// 他の生成される関数を明示的に定義する必要がある(C.21)
// ...
};
class Good { // より効率的
string s = "default";
int i = 1;
public:
// コンパイラが生成したデフォルトコンストラクタを使う
// ...
};
悪い例
class Date {// Bad: 似たコードの繰り返しがある。
int d;
Month m;
int y;
public:
Date(int ii, Month mm, year yy)
:i{ii}, m{mm} y{yy}
{ if (!valid(i, m, y)) throw Bad_date{}; }
Date(int ii, Month mm)
:i{ii}, m{mm} y{current_year()}
{ if (!valid(i, m, y)) throw Bad_date{}; }
// ...
};
99.
良い例
class Date2 {
intd;
Month m;
int y;
public:
Date2(int ii, Month mm, year yy)
:i{ii}, m{mm} y{yy}
{ if (!valid(i, m, y)) throw Bad_date{}; }
// 他のコンストラクタを呼び出す。
Date2(int ii, Month mm)
:Date2{ii, mm, current_year()} {}
// ...
};