赋值运算符

来源:互联网 发布:js中使用map集合 编辑:程序博客网 时间:2024/06/09 17:05

对于赋值运算符正常需要考虑4点

1.传入参数是否是常量引用

2.返回类型是否是类的引用

3.是否释放自身已占的内存

4.是否考虑自赋值情况

对于异常安全性,普通赋值运算符定义如下,存在m_data的内存不足以New一个新char,将会导致m_data=NULL

CMyString& CMyString::operator = (const CMyString &other) {      if (this == &other) {          return *this;      }      else {          delete []m_data;          m_data = NULL;          m_data = new char[strlen(other.m_data) + 1];  //m_data内存不足,抛出异常        strcpy(m_data, other.m_data);          return *this;             }  }  
考虑异常,采用如下表示,临时变量strTemp在离开作用域时将会自动调用析构函数
CMyString& CMyString::operator = (const CMyString &other) {      if (this == &other) {          return *this;      }      else {          CMyString strTemp(other);          char* pTemp = strTemp.m_data;          strTemp.m_data = m_data;          m_data = pTemp;          return *this;      }  } 
补充:
c++ effective条款三,对于其他运算符,更高效的书写方式如下

class Rational{...};const Rational operator*(const Rational &lhs,const Rational &rhs);
为什么要加const,加const表明返回值为不可更改的,就不会出现

Rational a,b,c;

(a*b)=c;的暴行

例如只想判断if(a*b=c),但少写了一个=,所以声明为const可以省下很多麻烦