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

void logCall(const std::string & funcName);
class Customer {
public:
	Customer(const Customer & rhs);
	Customer& operator= (const Customer& rhs);
private:
	std::string name;
};

Customer::Customer(const Customer & rhs): name(rhs.name) {
	logCall("Customer copy constructor");
}

Customer& Customer::operator=(const Cutomer& rhs) {
	logCall("Customer copy assignment operator");
	name = rhs.name;	// 复制rhs的数据
	name = rhs.name;
	return *this;
}

但是如果添加一个新的成员变量, 如下

class Date{};
class Customer {
public:
	// 同上
private:
	std::string name;
	Date lastTransaction;
};

  这时既有copying函数执行的是局部拷贝(partial copy): 它们的确赋值了顾客的name, 但没有复制新添加的lastTransaction。同理, 如果出现继承, 更有危机。

class PriorityCustomer:public Customer {
public:
	PriorityCustomer(const PriorityCutomer &rhs);
	PriorityCustomer & operator=(const PriorityCutomer &rhs);
private:
	int priority;
}


//  错误
PriorityCustomer::PriorityCustomer(const PriorityCustomer &rhs): priority(rhs.priority) {
	logCall("PriorityCustomer copy constructor");
}

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

// 正确
PriorityCustomer::PriorityCutomer(const PriorityCustomer& rhs): Customer(rhs), priority(rhs.priority) {
	logCall("PriorityCustomer copy constructor");
}

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

总结:

  • Copying函数应该确保赋值“对象内的所有成员变量”及“所有base class成分”。
  • 不要尝试以某个copying函数实现另一个copying函数。 应该将共同机能放进第三个函数中, 并由两个copying函数共同调用。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值