Effective-cpp-#12

copy all parts of an object

动机

  • 局部的拷贝,编译器是允许的。假如你自定义了一个拷贝构造函数或者拷贝复制函数,但函数内部只复制了部分的成员变量,那么编译器并不会报错。
  • 另一个问题是在继承时,由于子类无法访问基类的私有变量,那么拷贝构造函数可能会没有拷贝所有成员变量,而是由基类的default constructor初始化成员变量;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Customer{
public:
...
private:
std::string name;
Date last;
};

class PriorityCustomer: public Customer{
public:
PriorityCustomer(const PriorityCustomer& rhs):priority(rhs.prioruty){}
//在这种情况,基类成员的初始化是在default constructor中完成的
PriorityCustomer& operator=(const PriorityCustomer& rhs){
priority = rhs.priority;
return *this;
}
private:
int priority;
};

解决方法

  • 针对第一种情况,要注意在修改类之后,要同时修改两个拷贝函数;
  • 第二情况,则需要让派生类去调用基类的copy函数;
1
2
3
4
5
6
7
PriorityCustomer(const PriorityCustomer& rhs):Customer(rhs) ,priority(rhs.prioruty){}
//分别调用基类的copy函数
PriorityCustomer& operator=(const PriorityCustomer& rhs){
Customer::operator=(rhs);
priority = rhs.priority;
return *this;
}

注意问题

  • 不应该在copy assignment操作符函数中调用copy构造函数,因为这相当于初始化一个已经存在存在的对象,这没意义,并且增加复杂度;
  • 也不应该在copy构造函数中调用copy assignment操作符,这相当于在一个尚未初始化的对象身上做“对已经初始化的对象的操作”;
  • 往往以上两种操作都很有可能造成循环调用;