Effective C++ 学记之12 复制对象时勿忘其每一个成分

copying函数应该确保复制“对象内的所有成员变量”及“所有base class成分”。


不要尝试以某个copying函数实现另一个copying函数。应该将共同机能放进第三个函数中,并由两个copying函数共同调用。


这里说的copying函数指的是“copy构造函数”和“copy赋值操作符”。前面的条款讲到,当用户自己定义copying函数时,编译器不会生成默认的copying函数。
如下面的例子:

void logCall(const std::string& funcName); //制造一个log 入口
class  Customer{
public:
    ...
    Customer(const Customer& rhs);//copy构造函数
    Customer& operator=(const Customer& rhs);//copy赋值操作符
    ...
private:
    std::string name;
};
Customer::Customer(const Customer& rhs):name(rhs.name)
{
    logCall("Customer copy constructor");
}
Customer& Customer::operator=(const Customer& rhs)
{
    logCall("Customer copy assignment operator");
    name = rhs.name;
    return *this;
}
到上面为止,所有事情看起来都很好,直到另一个成员变量加入:

class Date{...};
class  Customer{
public:
    ...
private:
    std::string name;
    Date lastTransaction;//增加一个成员变量
};
这时如果不同时修改copying函数,就只执行了name的copy,没copy新添加的lastTransaction。编译器也不会报错。
因此: 如果你为class添加一个成员变量,必须同时修改copying函数。

一旦发生继承,也会出现麻烦:
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)
{
    logCall("PriorityCustomer copy constructor");
}
PriorityCustomer& PriorityCustomer::operator(const PriorityCustomer& rhs)
{
    logCall("PriorityCustomer copy assighment operator");
    priority = rhs.priority;
    return *this;
}
由于上面PriorityCustomer的copying函数并未制定实参传给起base class构造函数,因此PriorityCustomer的Customer成分会被不带实参的default构造函数初始化。
name和lastTransaction将被缺省初始化。

解决方案:让derived class的copying函数调用相应的base class函数:

PriorityCustomer:PriorityCustomer(const PriorityCustomer& rhs):Customer(rhs),priority(rhs.priority)//调base class的copy构造函数
{
    logCall("PriorityCustomer copy constructor");
}
PriorityCustomer& PriorityCustomer::operator(const PriorityCustomer& rhs)
{
    logCall("PriorityCustomer copy assighment operator");
    Customer::operator=(rhs);//对base class进行赋值动作
    priority = rhs.priority;
    return *this;
}
编写一个copying函数请把握好:
1 复制所有local成员变量。
2 调所有base classes内的适当copying函数。

另外不该令copy assignment操作符调用copy构造函数,因为这样会像试图构造一个已经存在的对象,是不合理的。。应该将共同机能放进第三个函数中,并由两个copying函数共同调用。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值