“编译器生成版”的copy构造函数和copy assignment操作符行为:将被拷对象的所有成员变量都做一份copy。
如果你声明自己的copying函数,意思就是告诉编译器不喜欢缺省实现中的某些行为。编译器仿佛被冒犯似的,会以一种奇怪的方式回敬:当你的实现代码几乎必然出错时却不告诉你。
直接看例子:
class Customer {
public:
Customer(const Customer& rhs);
Customer& operator=(const Customer& rhs);
private:
std::string name;
};
Customer::Customer(const Customer& rhs) : name(rhs.name)
{
}
Customer& Customer::operator=(const Customer& rhs)
{
name = rhs.name;
return *this;
}
上面代码没问题,直到另一个成员变量加入战局:
class Date {
};
class Customer {
public:
Customer(const Customer& rhs);
Customer& operator=(const Customer& rhs);
private:
std::string name;
Date lastTransaction;//新增加成员变量
};
这时候已有的copying函数执行的是局部拷贝:它们的确复制了顾客的name,但没有复制新添加的lastTransaction。大多数编译器对此不出任何怨言——即使在最高警告级别中。结论很明显:如果你为class添加一个成员变量,就必须同时修改copying函数定义实现部分。(此外,也需要修改class的所有构造函数以及任何非标准形式的operator=)
一旦发生继承,可能会造成此一主题的一个潜藏危机。看个例子:
class PriorityCustomer : public Customer {
public:
PriorityCustomer(const PriorityCustomer& rhs);
PriorityCustomer& operator=(const PriorityCustomer& rhs);
private:
int priority;
};
PriorityCustomer::PriorityCustomer(const PriorityCustomer& rhs) : priority(rhs.priority)
{
}
PriorityCustomer& PriorityCustomer::operator=(const PriorityCustomer& rhs)
{
priority = rhs.priority;
return *this;
}
PriorityCustomer的copying函数看起来好像复制了PriorityCustomer内的每一样东西,但是仔细看发现,虽然它们复制了PriorityCustomer声明的成员变量,但每个PriorityCustomer还内含它所继承的Customer成员变量副本,而那些成员变量却没被复制。PriorityCustomer的copy构造函数并没有指定实参传递给其base class构造函数(也就是说它在它的成员初值列中没有提到Customer),因此PriorityCustomer对象的Customer成分会被不带实参之Customer构造函数(即default构造函数——必定有一个否则无法通过编译)初始化。default构造函数将针对name和lastTransaction执行缺省的初始化动作。
任何时候只要你承担起“为derived class撰写copying函数”的重大责任,必须很小心的也复制其base class成分。那些成分往往是private,所以你无法直接访问它们,你应该让derived class的copying函数调用相应的base class函数:
PriorityCustomer::PriorityCustomer(const PriorityCustomer& rhs)
: Customer(rhs),//调用base class的copy构造函数
priority(rhs.priority)
{
}
PriorityCustomer& PriorityCustomer::operator=(const PriorityCustomer& rhs)
{
Customer::operator=(rhs);//对base class成分进行赋值动作
priority = rhs.priority;
return *this;
}
本条款题目所说的“复制每一个成分”现在应该很清楚了。当编写一个copying函数,请确保(1)复制所有local成本变量,(2)调用所有base class内的适当的copying函数。
令copy assignment操作符调用copy构造函数是不合理的,因为这就像试图构造一个已经存在的对象。记住:不该令copy assignment操作符调用copy构造函数。
反方向——令copy构造函数调用copy assignment操作符——同样无意义。构造函数用来初始化新对象,而assignment操作符只施行于已初始化对象身上。
如果发现你的copy构造函数和copy assignment操作符有相近的代码,消除重复代码的做法是,建立一个新的成员函数给两者调用。这样的函数往往是private而且被命名为init。这个策略可以安全消除copy构造函数和copy assignment操作符之间的代码重复。
要点:
1.copying函数(copy构造函数和copy assignment操作符)应该确保复制“对象内的所有成员变量”及“所有base class成分”。
2.不要尝试以某个copying函数实现另一个copying函数。应该将共同机能放进第三个函数中,并由两个copying函数共同调用。