String& String::operator=(const String& other) {
// (1) 自賦值檢查
if (this == &other) return *this;
// (2) 釋放舊資源
delete [] m_data;
// (3) 分配新記憶體並複製內容
int len = strlen(other.m_data);
m_data = new char[len + 1];
strcpy(m_data, other.m_data);
// (4) 返回 *this 支援鏈式賦值
return *this;
}
a = a,間接自賦值 b=a; c=b; a=c; 或 b=&a; a=*b; 同樣致命。delete → 物件自殺後無法複製自己。strlen 不含 \0,strcpy 含 \0,故分配 len+1。*this 而非 this 或 other:
return this → 型別錯誤 (指標 vs 參考)。return other → 危險!other 可能是臨時物件,賦值結束即銷毀,返回懸空參考。若類別**不應被複製**(如獨佔資源、單例、IO 通道),只需宣告為 private **且不實作**:
class A {
private:
A(const A&); // 未定義
A& operator=(const A&); // 未定義
};
任何嘗試複製/賦值的代碼將**編譯報錯** (存取 private),完美封鎖編譯器預設的淺拷貝。C++11 後可用 = delete 更明確。
virtual**,確保多態刪除正確調用派生類解構函數。