赋值运算符重载

//添加赋值运算符函数:

CMyString& CMystring::operator=(const CMyString& str){
    if (this == &str)
        return *this;
    delete []m_pData;
    m_pData = nullptr;
    m_pData = new char[strlen(str.m_pData)+1];
    strcpy(m_pData, str.m_pData);  //数组字符串的拷贝
    return *this;
}
// 考虑异常安全性:先用new分配新内容,再用delete释放已有的内容
// 保证由于内存不足抛出异常时,还没有修改原来实例的状态
CMyString& CMyString::operator=(const CMyString& str){
    if (this != &str){
        CMyString tmpStr(str);
        char* pTempData = tmpStr.m_pData;
        tmpStr.m_pData = m_pData;
        m_pData = pTempData;
    }
    return *this;
}
原文地址:https://www.cnblogs.com/songdanzju/p/7441932.html