标签:this cep strlen 类型 代码 rhs 移动赋值 内存 new
首先看拷贝构造函数:
//拷贝构造函数
A(A& t)
{
if(t.text!=NULL)
{
int len=strlen(t.text);
text=new char[len+1];
strcpy(text,t.text);
}
}
拷贝构造函数中实现了深拷贝处理。再看移动构造函数:
//移动构造函数
A(A&& t)
{
if(t.text!=NULL)
{
text=t.text;
t.text=NULL;
}
}
代码构造和拷贝构造函数类似,但是内存的处理不是拷贝而是转移。注意参数类型是右值引用。
移动赋值运算符
赋值运算符的情况和构造函数类似,还是先考察普通的赋值运算符:
//拷贝赋值运算符
A& operator=(const A& rhs)
{
if(this!=&rhs)
{
free();
if(rhs.text!=NULL)
{
int len=strlen(rhs.text);
text=new char[len+1];
strcpy(text,rhs.text);
}
}
return *this;
}
再看移动赋值运算符:
//移动赋值运算符
A& operator=(A&& rhs)noexcept
{
if(this!=&rhs)
{
free();
text=rhs.text;
rhs.text=NULL;
}
reeturn *this;
}
标签:this cep strlen 类型 代码 rhs 移动赋值 内存 new
原文地址:https://www.cnblogs.com/wuyepeng/p/9787993.html