实际中我们常会遇到重载赋值操作符的情况,所以今天来稍微提下其中遇到的一些坑。
先来看一个普通的例子:
class Test
{
public:
Test()
{
data = new char[100];
}
Test& operator=(const Test& t);
private:
char *data;
};
Test& Test::operator=(const Test& t)
{
delete data;
data = new char(strlen(t.data)+1);
strcpy(data,t.data);
return *this;
}
乍一看,好像没什么问题,但是如果赋值给自己呢?,比如:
int main()
{
Test t1;
strcpy(t1.data,"zhaocl");
t1=t1;
return 0;
}
可以看到,赋值并没有成功,其实看代码也能看出来,因为t 和*this指向同样的对象。
解决方案1:(先判断是不是自身)
if(&t != this)
{
//...赋值
}
return *this;
解决方案2:(先保存旧值)
char *newData = new char[strlen(t.data)+1];
strcpy(newData,s.data);
delete data;
data = newData;
return *this;