對於一個空類 class Empty {},編譯器會隱式生成以下 public 成員函數:
Empty()Empty(const Empty&)Empty& operator=(const Empty&)~Empty()(非 virtual,除非基類有 virtual 析構)operator&()(const 和非 const 版本)const、reference 或無默認構造的成員時,編譯器拒絕生成對應函數(報錯)。private 可阻止編譯器為其生成對應函數(C++11 可用 = delete)。C++ 無運行期檢查機制,運行期錯誤(如空指針解引用、越界)極難定位。策略:
Date(int d, Month m, int y) 中 Month 為類而非 enum 或 int,構造函數 private,只提供 static Month Jan() 等工廠方法,杜絕非法月份值構造。非局部靜態對象:全局/命名空間變量、類靜態成員、文件級 static 變量。跨編譯單元的初始化順序未定義,易導致「初始化順序災難」。
class Country { /* ... */ };
Country& theCountry() {
static Country instance; // 首次調用時初始化,線程安全 (C++11)
return instance;
}
// 使用時:theCountry().doSomething();
優勢:
/W4 MSVC, -Wall -Wextra -pedantic GCC/Clang)。B::f() hides virtual A::f() 提示派生類非 const 重載隱藏了基類 const 虛函數,導致多態失效。/WX / -Werror)強制修復。| 條款 | 核心建議 | 關鍵技術 |
|---|---|---|
| 45 | 掌握編譯器隱式生成的六大函數行為 | 淺拷貝、const/ref 成員限制、private 禁用生成 |
| 46 | 錯誤前移至編譯期 | 強類型封裝、private 構造+工廠方法 |
| 47 | 消除非局部靜態初始化順序依賴 | Meyers Singleton (函數局部 static) |
| 48 | 零容忍編譯器警告 | 高警告級、多編譯器、警告即錯誤 |