zoukankan      html  css  js  c++  java
  • 类的赋值运算符的重载函数

    题目:类CMyString的声明如下,请实现其赋值运算符的重载函数,要求异常安全,即当对一个对象进行赋值时发生异常,对象的状态不能改变。

    class CMyString
    {
    public:
        CMyString(char* pData = NULL);
        CMyString(const CMyString& str);
        CMyString& operator = (const CMyString& str);
        ~CMyString();
    
    private:
        char* m_pData;
    };

    答:

    //1、可能有异常
    CMyString& CMyString::operator = (const CMyString& str)
    {
        if (this != &str)
        {
            delete [] m_pData;
            m_pData = NULL;
            m_pData = new char[strlen(str.m_pData) + 1]; //这里内存分配不成功,之前的数据已经释放,不安全
            strcpy(m_pData, str.m_pData);
        }
        return *this;
    }
    
    //2、异常安全
    CMyString& CMyString::operator = (const CMyString& str)
    {
        if (this != &str)
        {
            CMyString tmp(str);
            char *pTmp = m_pData;
            m_pData = tmp.m_pData;
            tmp.m_pData = pTmp;
        }
        return *this;
    }
  • 相关阅读:
    odoo10 入门
    git 命令详细介绍
    odoo中Python实现小写金额转换为大写金额
    {DARK CTF } OSINT/Eye
    2020 12 18
    2020 12 17
    2020 12 16
    2020 12 15
    2020 11 14
    2020 11 13
  • 原文地址:https://www.cnblogs.com/venow/p/2666873.html
Copyright © 2011-2022 走看看