实现赋值运算符重载函数,确保:
- 新的数据可准确地被复制
- 旧的数据可准确地删除/释放
- 可进行
A = B = C
赋值
样例
如果进行 A = B
赋值,则 A 中的数据被删除,取而代之的是 B 中的数据。
如果进行 A = B = C
赋值,则 A 和 B 都复制了 C 中的数据。
挑战
充分考虑安全问题,并注意释放旧数据。
说明
本题只适用于C++
,因为 Java 和 Python 没有对赋值运算符的重载
class Solution {
public:
char *m_pData;
Solution() {
this->m_pData = NULL;
}
Solution(char *pData) {
if(this->m_pData != NULL)
delete m_pData;
this->m_pData = new char[strlen(pData) + 1];
strcpy(this->m_pData, pData);
//this->m_pData = pData;
}
// Implement an assignment operator
Solution operator=(const Solution &object)
{
if (this == &object) {
return *this;
}
if(object.m_pData == NULL)
{
m_pData = NULL;
return *this;
}
char *temp = this->m_pData;;
// write your code here
// if(this->m_pData != NULL)
// delete m_pData;
this->m_pData = new char[strlen(object.m_pData) + 1];
strcpy(this->m_pData, object.m_pData);
if(temp)
delete temp;
return *this;
}
};