operator=返回一个reference to * this
协议:赋值操作符必须返回一个reference指向操作符(&)的左侧实参。
class Widget{
public:
...
Widget& operator=(const Widget& rhs)
{
...
return* this;
}
};
- 该协议适用于所有赋值相关运算
- 只是协议,如果不遵循代码一样可通过编译
- 所有内置类型和标准程序库提供的类型如string,vector,complex,trl::shared_ptr共同遵守该协议。
“自我赋值”
自我赋值有时并不明显,由别名引起。
a[i]=a[j];//潜在的自我赋值i=j
*px=*py;//潜在的自我赋值,px和py指向同一变量;
可能会导致在停止使用资源之前意外释放了它,例如:
class Bitmap{...};
class Wiget
{
...
private:
Bitmap* pb;
}
Wiget::operator= (const Wiget& rhs)
{
delete pb; //停止使用当前的bitmap。如果this和rhs指向同一对象会出问题
pb = new Bitmap(*rhs.pb);//使用rhs的bitmap的副本。
return *this;
}
可以通过“证同”或者“copy and swap”解决该问题。
//证同
Wiget::operator = (const Wiget& rhs)
{
if(this == &rhs)return *this; //证同测试,如果是自我赋值,就不作任何事
delete pb;
pb = new Bitmap(*rhs.pb);
return *this;
}
//copy and swap
Widget& Widget::operator = (const Widget& rhs)
{
Bitmap* pOrig = pb; //记住原先的pb
pb = new Bitmap(*rhs.pb);//令pb指向*pb的一个副件
delete pOrig; //删除原先的pb
return *this;
}
复制对象时勿忘每一个成分(派生类继承基类的成分)
如果自己声明coping函数(copy构造函数和copy assignment操作符),而不使用编译器缺省实现的某些行为。会导致编译器在你的实现代码几乎必然出错时却不告诉你,因此必须小心地复制base class成分。
如果你为类添加一个成员变量,你必须同时修改coping函数,也需要修改class的所有构造函数以及任何非标准形式的operator=
如果派生类的copy构造函数并没有指定实参传给其base class构造函数,则派生类对象的基类成分会被不带实参之基类构造函数初始化
//错误示范--没有指定实参传给其base class构造函数 class PriorityCustomer:public Customer { public: PriorityCustomer(const PriorityCustomer& rhs); PriorityCustomer& operator=(const PriorityCustomer& rhs); ... private: int priority; };
//纠正示范--指定实参传给其base class构造函数 PriorityCustomer::PriorityCustomer(const PriorityCustomer& rhs) :Customer(rhs),priority(rhs.priority) //调用base class的copy构造函数 {} PriorityCustomer& PriorityCustomer::operator = (const PriorityCustomer& rhs) { Customer::operator=(rhs); //对base class成分进行赋值动作 priority=rhs.priority; return *this; }
PS:如果copy构造函数和copy assignment操作符有相近的代码,可以建立一个新的成员函数给两者调用。该函数一般是private。