類持有動態分配資源(如 Bitmap* pb),operator= 若不檢查自我賦值會導致資源釋放後再讀取已釋放內存。
Widget& Widget::operator=(const Widget& rhs) {
if (this == &rhs) return *this;
delete pb;
pb = new Bitmap(*rhs.pb);
return *this;
}
Widget& Widget::operator=(const Widget& rhs) {
Bitmap* pOrig = pb;
pb = new Bitmap(*rhs.pb); // 可能拋出異常,但原資源未釋放
delete pOrig;
return *this;
}
Widget& Widget::operator=(Widget rhs) { // 參數傳值自動調用拷貝構造
swap(rhs); // 交換內部資源
return *this; // rhs 析構釋放舊資源
}
優點:異常安全、碼簡潔、天然處理自我賦值。需提供 swap 成員函數( noexcept)。