MyString& MyString::operator=(const MyString& str) {
if (this == &str) return *this;
delete[] m_pData; // 為什麼要釋放?
m_pData = NULL;
m_pData = new char[strlen(str.m_pData) + 1];
strcpy(m_pData, str.m_pData);
return *this;
}
若直接賦值 m_pData = str.m_pData,原 m_pData 指向的內存塊失去引用,無法被釋放,造成內存洩漏。長期運行程序會耗盡堆內存。
若執行 m_pData = str.m_pData,兩對象共享同一內存塊:
MyString s1("hello"), s2("world");
s1 = s2; // 淺拷貝後 s1.m_pData == s2.m_pData
s2.m_pData[0] = 'W'; // 修改 s2 導致 s1 內容也變為 "World"
這違背了賦值語義:s1 = s2 後修改 s2 不應影響 s1(類似 int a=b; b=3; a 仍為原值)。
MyString& MyString::operator=(MyString other) { // 參數傳值觸發拷貝構造
swap(*this, other); // 交換內部指針
return *this; // other 析構時釋放舊內存
}
void swap(MyString& a, MyString& b) noexcept {
std::swap(a.m_pData, b.m_pData);
}
if (this == &str)delete[] m_pDatanew char[len+1]strcpy*this 支持鏈式賦值