为什么赋值运算符要防止自身赋值呢??
如果类里面含有指针指向动态分配的资源的话,那么自身赋值就可能出错
有可能导致把自己给释放了
如下面:
#include<iostream>
#include<string>
#include<string.h>
using namespace std;
class A
{
public:
char *ptr;
A(){ptr = nullptr;}
void set_ptr(char *str){ptr = new char[strlen(str)+1]; strcpy(ptr,str);}
A& operator=(const A&rhs)
{
delete ptr;
ptr = new char[strlen(rhs.ptr)+1];
strcpy(ptr,rhs.ptr);
return *this;
}
};
int main()
{
A a;
a.set_ptr("hello world");
a = a;
cout<<a.ptr<<endl;
}
//导致输出错误
下面有几种办法
1、判断参数是否是自身
那么就要重载==或者!=运算符
if(*this != rhs)
该运算符不止要判断数据成员的值是否相等
还要判断ptr的指向(即ptr的指针值是否相等)
那么这样的运算符失去了一般性(没必要判断ptr的指针值是否相等,而是判断指向的内容是否相等)
2、即先将右操作数的内容赋值到一个临时指针
然后释放左操作数指针指向的内存
然后将临时指针赋给左操作数的指针
class A
{
public:
char *ptr;
A(){ptr = nullptr;}
void set_ptr(char *str){ptr = new char[strlen(str)+1]; strcpy(ptr,str);}
A& operator=(const A&rhs)
{
char *temp = new char[strlen(rhs.ptr)+1];//复制资源到一个临时指针
strcpy(temp,rhs.ptr);
delete ptr;
ptr = temp;
return *this;
}
};
当然了,具体情况还是得针对类的具体实现来考虑
明白这个思想就行了