[剑指offer] 赋值运算符重载

http://www.lintcode.com/zh-cn/problem/assignment-operator-overloading-c-only/#

还是有很多点需要注意的。

  1. 判断this与传入的object是否是同一个对象,相同的话直接返回*this就可以了。
  2. 判断传入对象的数组是否为空,空的话就不必复制,直接释放内存并将指针置NULL即可。
  3. 考虑异常安全。因为new char[]时如果内存不足会抛出异常,这时安全的做法是先尝试申请内存,申请成功后再释放原来的内存,如果申请失败原来的数据还在。
class Solution {
public:
    char *m_pData;
    Solution() {
        this->m_pData = NULL;
    }
    Solution(char *pData) {
        this->m_pData = pData;
    }

    // Implement an assignment operator
    Solution& operator=(const Solution &object) {
        if (this == &object) {
            return *this;
        }
        
        if (!object.m_pData) {
            if (m_pData) delete[] m_pData;
            m_pData = NULL;
            return *this;
        }
        
        char *tmp = m_pData;
        try {
            m_pData = new char[strlen(object.m_pData) + 1];
            strcpy(m_pData, object.m_pData);
            if (tmp) delete[] tmp;
        } catch (bad_alloc& e) {
            m_pData = tmp;
        }
        
        return *this;
    }
};
原文地址:https://www.cnblogs.com/ilovezyg/p/6947636.html