zoukankan      html  css  js  c++  java
  • 改善程序与设计的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 }
  • 相关阅读:
    难得之货,令人行妨
    Oracle死锁
    log4j杂记
    Oracle9或11使用了Oracle10的驱动引起的时间丢失
    程序员要重视过劳
    oracle提供的有用函数(待续)
    Mysql扩展之replication概述
    @autowired与@qualifer的使用区别备忘
    Oracle中的in参数的个数限制
    java版正则式提取替换示例
  • 原文地址:https://www.cnblogs.com/cuish/p/5911234.html
Copyright © 2011-2022 走看看