operator=?預設賦值運算子執行淺層複製:逐位元複製成員。若類別包含指標成員,會導致兩物件指向同一塊堆記憶體,析構時雙重釋放 (double free) 或記憶體洩漏。
#include <iostream>
#include <cstring>
class Date {
int mo, da, yr;
char *month; // 動態配置字串
public:
Date(int m=0, int d=0, int y=0);
~Date();
Date& operator=(const Date& rhs); // 回傳 *this 參考,支援鏈式賦值
void display() const;
};
// 建構子
Date::Date(int m, int d, int y) : mo(m), da(d), yr(y), month(nullptr) {
static const char *mos[] = {"January","February","March","April","May","June",
"July","August","September","October","November","December"};
if (m != 0) {
month = new char[std::strlen(mos[m-1]) + 1];
std::strcpy(month, mos[m-1]);
}
}
// 解構子
Date::~Date() {
delete [] month;
}
// 重載賦值運算子
Date& Date::operator=(const Date& rhs) {
if (this != &rhs) { // 1. 自我賦值檢查
mo = rhs.mo; // 2. 複製基本型別成員
da = rhs.da;
yr = rhs.yr;
delete [] month; // 3. 釋放舊資源
if (rhs.month) { // 4. 深層複製指標成員
month = new char[std::strlen(rhs.month) + 1];
std::strcpy(month, rhs.month);
} else {
month = nullptr;
}
}
return *this; // 5. 回傳 *this
}
void Date::display() const {
if (month) std::cout << month << ' ' << da << ", " << yr << '\n';
}
int main() {
Date birthday(8, 11, 1979);
Date newday(12, 29, 2003);
newday = birthday; // 呼叫 operator=
newday.display(); // 輸出 August 11, 1979
return 0;
}
if (this != &rhs) 避免釋放自己資源。std::string、智慧指標等可直接賦值。delete/free/close 等。*this:支援 a = b = c 鏈式賦值。class Date {
// ... 成員相同 ...
friend void swap(Date& a, Date& b) noexcept {
using std::swap;
swap(a.mo, b.mo);
swap(a.da, b.da);
swap(a.yr, b.yr);
swap(a.month, b.month); // 指標交換,無需 new/delete
}
public:
Date& operator=(Date rhs) { // 以值傳遞參數 (複製建構子產生副本)
swap(*this, rhs); // 交換內容
return *this; // rhs 攜帶舊資源離開作用域,析構自動釋放
}
};
swap 且析構子正確。| 規則 | 需自訂的特殊成員函式 | 適用場景 |
|---|---|---|
| Rule of Three (C++98) | 解構子、複製建構子、賦值運算子 | 管理原始資源 (指標、檔案控制代碼、Socket) |
| Rule of Five (C++11) | + 移動建構子、移動賦值運算子 | 需高效轉移資源所有權 |
| Rule of Zero (現代最佳) | 無需自訂任何特殊成員 | 使用 std::string、std::vector、std::unique_ptr 等 RAII 類型封裝資源 |
重載賦值運算子核心在於深層複製資源、防禦自我賦值、提供強烈異常安全。現代 C++ 強烈建議遵循 Rule of Zero:以標準庫 RAII 容器/智慧指標取代原始指標,讓編譯器自動生成正確的特殊成員函式,徹底杜絕記憶體管理錯誤。