Foo& Foo::operator=(const Foo& f) {
return *new Foo(f); // 每次賦值 new 一個對象,無人 delete
}
a = b = c 會洩漏多塊內存。Foo& Foo::operator=(Foo other) { // 參數按值傳遞,觸發拷貝構造
swap(*this, other); // 交換內部資源
return *this; // other 析構時釋放舊資源
}
void swap(Foo& a, Foo& b) noexcept {
using std::swap;
swap(a.ptr_, b.ptr_); // 假設內部有裸指針或資源句柄
}
Foo& operator=(Foo&& other) noexcept {
if (this != &other) {
delete ptr_;
ptr_ = other.ptr_;
other.ptr_ = nullptr;
}
return *this;
}
賦值運算符必須**釋放舊資源、接管新資源、返回 \*this**,絕不返回 new 對象。