改善程序与设计的55个具体做法 day4

 

今天晚上回到小区门口,买了点冬枣,要结账的时候想起来,钥匙没带,落公司了!

TNND,没办法再回趟公司,拿了钥匙,来回一个小时,汗~

 

条款10:令operator=返回一个reference to *this

即赋值操作符返回引用。

原型 Object& operator=(const Object& obj)

 

同时,该协议还适用于所有的赋值操作。

Object& operator=(int a)等形式

 

 

条款11:在operator=中处理“自我赋值”

1 Object& operator(const Object& obj)
2 {
3     if ( this != &obj)
4     {
5         // do something
6     }
7 
8     return (*this);
9 }

 

这种情况会在a[ i ] = a[ j ] 这种情况下表现的很隐藏,当类中有指针成员,而指针成员指向一段动态申请的内存时容易出问题。

该条款中介绍了一种【copy and swap】的技术: 

 

 1 // 参数为引用
 2 CObject& operator=(const CObject& obj)
 3 {
 4     if ( this != &obj )
 5     {
 6         CObject objTemp(obj);    // objTemp中的数据为obj数据的一份拷贝
 7         swap(objTemp);             // this 数据与objTemp的数据交换
 8     }
 9 
10     return ( *this );
11 }
12 
13 
14 15 
16 
17 // 参数非引用
18 CObject& operator=( CObject obj)
19 {
20     if ( this != &obj )
21     {         
22         swap(obj);             // this 数据与作为实参副本的obj对象的数据交换
23     }
24 
25     return ( *this );
26 }

 

posted on 2016-09-27 00:00  崔好好  阅读(154)  评论(0编辑  收藏  举报

导航