假设我们有以下内容:
class StringClass
{
public:
...
void someProcessing( );
...
StringClass& operator=(const StringClass& rtSide);
...
private:
char *a;//Dynamic array for characters in the string
int capacity;//size of dynamic array a
int length;//Number of characters in a
};
StringClass& StringClass::operator=(const StringClass& rtSide)
{
capacity = rtSide.capacity;
length = rtSide.length;
delete [] a;
a = new char[capacity];
for (int i = 0; i < length; i++)
a[i] = rtSide.a[i];
return *this;
}
我的问题是:为什么当我们尝试将对象分配给自身时,这种重载赋值运算符的实现会导致问题,例如:
StringClass s;
s = s;
我正在阅读的教科书(Absolute C++)说,在delete [] a;
“指针 sa 未定义。赋值运算符损坏了对象 s 并且该程序的运行可能被破坏了”之后。
为什么运营商破坏了s?如果我们在删除 sa 后立即重新初始化它,为什么这会导致程序中出现这样的问题,我们必须将函数重新定义为:
StringClass& StringClass::operator=(const StringClass& rtSide)
{
if (this == &rtSide)
//if the right side is the same as the left side
{
return *this;
}
else
{
capacity = rtSide.capacity;
length = rtSide.length;
delete [] a;
a = new char[capacity];
for (int i = 0; i < length; i++)
a[i] = rtSide.a[i];
return *this;
}
}