《Effective C++》条款12:复制对象别忘了每一个成分
本章主要讲述了两大复制函数(符号赋值和赋值函数)的存在问题,这次是第一次接触,所以没有什么印象;
关于类内成员可能遗漏的问题:
如果我们不对函数进行指定,不适用默认的赋值函数,会导致编译器不会对复制对象进行检查,换句话说就是无论漏掉成员也不会报错;
因此,我们在制定赋值函数,必须要对操作负责,所以每次增加一个成员变量的时,必须要同时对copy函数进行修改;
关于继承下的copy函数问题:
当存在继承关系的时候,也要对基类进行参数传递;
主要原因:因为copy函数不存在调用链,不像构造函数那样,会从基类进行构造,因此需要我们手动传参给基类的copy函数;
class Data {};
class Customer {
public:
//...
private:
string name;
Data LastTransaction;
};
class PriorityCustomer :public Customer {
public:
PriorityCustomer(const PriorityCustomer& rhs);
PriorityCustomer& operator=(const PriorityCustomer& rhs);
private:
int priority;
};
PriorityCustomer::PriorityCustomer(const PriorityCustomer& rhs) :Customer(rhs), priority(rhs.priority) {
//...do something;
}
PriorityCustomer& PriorityCustomer::operator=(const PriorityCustomer& rhs) {
Customer::operator=(rhs);
priority = rhs.priority;
return *this;
}
如上所示:
值得注意的是符号copy和copy函数的写法;
其中符号copy是类似于重载的写法;
copy函数是类似于构造函数的写法,可以通过初始化值列表进行传递;
这两种写法用的比较少,需要注意一下;
注意一点:copy和符号copy不能相互调用,会涉及到初始化的问题;

浙公网安备 33010602011771号