Effective C++ 12:完整地拷贝对象

Item 12: Copy all parts of an object

在一个成熟的面向对象的C++系统中,只有两种拷贝对象的方式:复制构造函数赋值运算符,不妨称他们为拷贝函数。 拷贝函数属于编译器默认生成的函数(参考:Item 5:那些被C++默默地声明和调用的函数),默认的拷贝函数确实会完整地拷贝对象,但有时我们选择重载拷贝函数,问题就出在这里!

一个正确拷贝函数的实现是这样的:

class Customer{
  string name;
public:
  Customer(const Customer& rhs): name(rhs.name){}
  Customer& operator=(const Customer& rhs){
    name = rhs.name;                     // copy rhs's data
    return *this;                        // see Item 10
  }  
};

很完美对吧?但是有一天你新添加了一个数据成员,但忘记了更新拷贝函数:

class Customer{
  string name;
  Date lastTransaction;
public:
  Customer(const Customer& rhs): name(rhs.name){}
  Customer& operator=(const Customer& rhs){
    name = rhs.name;                     // copy rhs's data
    return *this;                        // see Item 10
  }  
};

这时lastTransaction便被被你忽略了,编译器也不会给出任何警告(即使在最高警告级别)。 另外一个常见的情形在你继承父类时:

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

上述代码看起来没有问题,但你忘记了拷贝父类的部分:

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

总之当你实现拷贝函数时,

  • 首先要完整复制当前对象的数据(local data);
  • 调用所有父类中对应的拷贝函数。

你可能注意到了代码的重复,但千万不要让复制构造函数和赋值运算符相互调用,它们的语义完全不同! C++甚至都没有提供一种语法可以让赋值运算符调用复制构造函数;反过来让复制构造函数调用赋值运算符倒是可以编译, 但由于复制构造函数的前置条件是一个未初始化的对象,而赋值运算符的前置条件是一个已初始化的对象。 这样的调用并非好的设计,恐怕会引起逻辑混乱。

但是代码重复怎么办?Scott Meyers提出可以抽象到一个普通方法中,比如init。是不是联想到了Objective-C的init函数?

本文采用 知识共享署名 4.0 国际许可协议(CC-BY 4.0)进行许可,转载注明来源即可: https://harttle.land/2015/08/01/effective-cpp-12.html。如有疏漏、谬误、侵权请通过评论或 邮件 指出。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值