条款12:复制对象时勿忘其每一个成分——87

文章目录


如果你声明自己的拷贝函数,意思就是告诉编译器你并不喜欢缺省实现中的某些行为。编译器仿佛被冒犯似的,会以一种奇怪的方式回敬:当你的实现代码几乎必然出错时却不告诉你。
考虑一个类用来表示顾客,其中手工写出(而非由编译器创建)拷贝函数,使得外界对它们的调用会被记录下来:

void logCall(const std::string& funcName);
class Customer{
public:
    ...
    Customer(const Customer& rhs);
    Customer& operator=(const Customer& ths);
    ...
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;
}

这时候既有的拷贝函数执行的是局部拷贝:它们的确复制了顾客的name,但没有复制新添加的lastTransaction。但是大多数编译器对此不作出任何警告。因此,如果你为class添加一个成员变量,你必须同时修改拷贝函数。
下面我们在考虑发生继承会出现的问题:

class PriorityCustomer:public Customer{
public:
    ...
    PriorityCustomer(const PriorityCustormer& rhs);
    PriorityCustomer& operator=(const PriorityCustomer& rhs);
    ...
private:
    int priority;
};
PriorityCustomer::PriorityCustomer(const PriorityCustomer& rhs):Priority(rhs.priority){
    logCall("PriorityCustomer copy constructor");
}

PriorityCustomer&
PriorityCustomer::operator=(cosnt PriorityCustomer& rhs){
    logCall("PriorityCustomer copy assignment operator");
    priority=rhs.priority;
    return *this;
}

上述代码的PriorityCustomer并没有复制它所继承的Customer成员变量复件。因此PriorityCustomer对象的Customer成分会被不带实参的Customer构造函数初始化。默认构造函数将针对name和lastTransaction执行缺省的初始化动作。
因此,任何时候请在派生类中的拷贝函数复制其基类的所有成员变量。 但是那些成员变量往往是private,所以你应该让派生类的构造函数调用相应的baseclass函数:

PriorityCustomer::PriorityCustomer(const PriorityCustomer& rhs):Customer(rhs),
      Priority(rhs.priority){
    logCall("PriorityCustomer copy constructor");
}

PriorityCustomer&
PriorityCustomer::operator=(cosnt PriorityCustomer& rhs){
    logCall("PriorityCustomer copy assignment operator");
    Customer::operator=(rhs);
    priority=rhs.priority;
    return *this;
}

总结——90

(1)拷贝函数应该确保复制“对象内的所有成员变量”及“所有基类成分”。
(2)不要尝试以某个拷贝函数实现另一个拷贝函数。应该将共同机能放进第三个函数中,并由两个拷贝函数共同调用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值