實作指派運算子(operator=)時,應回傳一個指向 *this 的參考,以支援鏈式指派(chained assignment)。
C++ 內建型別支援如下寫法:
int x, y, z;
x = y = z = 15; // 等價於 x = (y = (z = 15))
這要求 operator= 的回傳值可作為左值(lvalue)參與下一次指派。若回傳 void 或 by value,鏈式指派將無法編譯或行為錯誤。
class Widget {
public:
Widget& operator=(const Widget& rhs) {
// 1. 檢查自我指派
if (this == &rhs) return *this;
// 2. 釋放舊資源、複製新資源...
// 3. 回傳 *this 參考
return *this;
}
};
Widget&(非 const Widget&,否則 (a = b) = c 會失敗)。*this,代表目前物件的左值參考。if (this == &rhs) return *this;),避免釋放自身資源後再複製導致錯誤。std::sort 等要求可指派型別)。// 錯誤 1:回傳 void
void operator=(const Widget& rhs) { ... }
// 錯誤 2:回傳 by value(切割問題、效能差、無法鏈式)
Widget operator=(const Widget& rhs) { ... }
// 錯誤 3:回傳 const Widget&(無法 (a=b)=c)
const Widget& operator=(const Widget& rhs) { ... }
「令 operator= 回傳 *this 參考」是 C++ 類別設計的基石規範之一,確保物件語意與內建型別一致,支援標準演算法與直觀的鏈式指派語法。