若程式設計師不寫,編譯器**自動合成四個預設版本**:
A(); // 預設建構
A(const A&); // 預設拷貝建構 (位元拷貝)
~A(); // 預設解構
A& operator=(const A&); // 預設賦值 (位元拷貝)
若程式設計師說「寫這三個函數很簡單、不用動腦」,**認識仍淺、水平待提高**。這是無數前輩用血淚換來的教訓。
class String {
public:
String(const char* str = nullptr); // 普通建構
String(const String& other); // 拷貝建構
~String(); // 解構
String& operator=(const String& other); // 賦值
private:
char* m_data; // 動態字串緩衝區
};
本章將以此類為例,深入剖析教科書常忽略的關鍵細節。
~ + 類別名 (前綴區分,目的相反)。參考文獻:Thinking in C++ (Eckel) pp.55-56