1,两个理由,赋值操作必须特别谨慎可能发生的别名问题.
(1)效率,赋值操作中,如果一开始就检测到"自己赋值给自己",可以立刻返回.
(2)assignment运算符在为其左侧对象配置新资源之前,通常必须先将原先配置给左侧对象的所有资源释放掉.
如:
String& String::operator=(const String& rhs)
{
delete [] data; // delete old memory
// allocate new memory and copy rhs's value into it
data = new char[strlen(rhs.data) + 1];
strcpy(data, rhs.data);
return *this; // see Item 15
}
考虑下面的行为:
String a = "Hello";
a = a;
[img]http://dl.iteye.com/upload/attachment/251540/3bc3f1c8-e54e-34f4-b1da-bbf737fc420f.png[/img]
结果:
[img]http://dl.iteye.com/upload/attachment/251542/e93a9c2c-a009-3240-ad10-82fe4da6e37d.png[/img]
2,辨识两个对象是否为同一个.
String& String::operator=(const String& rhs)
(1)数值相等,if(*this==ths)
(2)内存地址相同,if(this==&ths)
(1)效率,赋值操作中,如果一开始就检测到"自己赋值给自己",可以立刻返回.
(2)assignment运算符在为其左侧对象配置新资源之前,通常必须先将原先配置给左侧对象的所有资源释放掉.
如:
String& String::operator=(const String& rhs)
{
delete [] data; // delete old memory
// allocate new memory and copy rhs's value into it
data = new char[strlen(rhs.data) + 1];
strcpy(data, rhs.data);
return *this; // see Item 15
}
考虑下面的行为:
String a = "Hello";
a = a;
[img]http://dl.iteye.com/upload/attachment/251540/3bc3f1c8-e54e-34f4-b1da-bbf737fc420f.png[/img]
结果:
[img]http://dl.iteye.com/upload/attachment/251542/e93a9c2c-a009-3240-ad10-82fe4da6e37d.png[/img]
2,辨识两个对象是否为同一个.
String& String::operator=(const String& rhs)
(1)数值相等,if(*this==ths)
(2)内存地址相同,if(this==&ths)