Item 12:完整地拷贝对象(拷贝构造函数、复制运算符) Effective C++笔记
来源:互联网 发布:php单选框提交 编辑:程序博客网 时间:2024/04/25 23:56
Item 12: Copy all parts of an object
在一个成熟的面向对象的C++系统中,只有两种拷贝对象的方式:复制构造函数和赋值运算符, 不妨称他们为拷贝函数。 拷贝函数属于编译器默认生成的函数(参考:Item 5:那些被C++默默地声明和调用的函数), 默认的拷贝函数确实会完整地拷贝对象,但有时我们选择重载拷贝函数,问题就出在这里!
一个正确拷贝函数的实现是这样的:
class Customer{ string name;public: Customer::Customer(const Customer& rhs): name(rhs.name){} Customer& 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::Customer(const Customer& rhs): name(rhs.name){} Customer& 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::PriorityCustomer(const PriorityCustomer& rhs) : priority(rhs.priority){} PriorityCustomer& PriorityCustomer::operator=(const PriorityCustomer& rhs){ priority = rhs.priority; } };
上述代码看起来没有问题,但你忘记了拷贝父类的部分:
class PriorityCustomer: public Customer {int priority;public: PriorityCustomer::PriorityCustomer(const PriorityCustomer& rhs) : Customer(rhs), priority(rhs.priority){} PriorityCustomer& PriorityCustomer::operator=(const PriorityCustomer& rhs){ Customer::operator=(rhs); priority = rhs.priority; } };
总之当你实现拷贝函数时,
- 首先要完整复制当前对象的数据(local data);
- 调用所有父类中对应的拷贝函数。
你可能注意到了代码的重复,但千万不要让复制构造函数和赋值运算符相互调用,它们的语义完全不同! C++甚至都没有提供一种语法可以让赋值运算符调用复制构造函数;反过来让复制构造函数调用赋值运算符倒是可以编译, 但由于复制构造函数的前置条件是一个未初始化的对象,而赋值运算符的前置条件是一个已初始化的对象。 这样的调用并非好的设计,恐怕会引起逻辑混乱。
但是代码重复怎么办?Scott Meyers提出可以抽象到一个普通方法中,比如
init
。是不是联想到了Objective-C的init
函数?
除非注明,本博客文章均为原创,转载请以链接形式标明本文地址: http://harttle.com/2015/08/01/effective-cpp-12.html
0 0
- Item 12:完整地拷贝对象(拷贝构造函数、复制运算符) Effective C++笔记
- 【C++】复制构造函数(拷贝构造函数)和=运算符重载使用的区别
- c++-拷贝构造函数(复制构造函数)
- 拷贝(复制)构造函数
- 赋值运算符复制构造函数(拷贝构造函数)易混处总
- 赋值运算符复制构造函数(拷贝构造函数)易混处总结
- C++之拷贝构造函数和复制运算符重载
- 对象的赋值、对象的复制(拷贝构造函数)
- 复制构造函数(拷贝构造函数)
- 复制构造函数(拷贝构造函数)
- 复制构造函数(拷贝构造函数)
- 复制构造函数(拷贝构造函数)
- 复制构造函数(拷贝构造函数)
- 复制构造函数(拷贝构造函数)
- 复制构造函数(拷贝构造函数)
- 复制构造函数(拷贝构造函数)
- 复制构造函数(拷贝构造函数)
- 复制构造函数(拷贝构造函数)
- nodejs 模板 ejs 入门 helloworld
- MySQL的管理,包括新建账户、基本信息查看
- POJ 题目 3693 Maximum repetition substring(后缀数组+RMQ+枚举求最小字典序的重复次数最多的子串)
- java.sql.SQLException: Incorrect string value: '\xE9\x99\xB6\xE4\xBC\x9F...' for column 'name' at ro
- 【Leetcode】Rotate Image
- Item 12:完整地拷贝对象(拷贝构造函数、复制运算符) Effective C++笔记
- 6.2 new 和 delete 运算符
- css的中英文对齐
- noip2001 car的旅行路线 (floyd求解最短路径长度)
- ImageView全屏
- linker command failed
- Item 13:使用对象(智能指针)来管理资源 Effective C++笔记
- MongoDB Query 的几个方法
- Android反编译工具及用法