http://www.lintcode.com/zh-cn/problem/assignment-operator-overloading-c-only/#
还是有很多点需要注意的。
- 判断
this
与传入的object
是否是同一个对象,相同的话直接返回*this
就可以了。 - 判断传入对象的数组是否为空,空的话就不必复制,直接释放内存并将指针置
NULL
即可。 - 考虑异常安全。因为
new char[]
时如果内存不足会抛出异常,这时安全的做法是先尝试申请内存,申请成功后再释放原来的内存,如果申请失败原来的数据还在。
class Solution {
public:
char *m_pData;
Solution() {
this->m_pData = NULL;
}
Solution(char *pData) {
this->m_pData = pData;
}
// Implement an assignment operator
Solution& operator=(const Solution &object) {
if (this == &object) {
return *this;
}
if (!object.m_pData) {
if (m_pData) delete[] m_pData;
m_pData = NULL;
return *this;
}
char *tmp = m_pData;
try {
m_pData = new char[strlen(object.m_pData) + 1];
strcpy(m_pData, object.m_pData);
if (tmp) delete[] tmp;
} catch (bad_alloc& e) {
m_pData = tmp;
}
return *this;
}
};