现在的位置: 首页 > 综合 > 正文

实现赋值操作符要注意的问题

2013年05月16日 ⁄ 综合 ⁄ 共 686字 ⁄ 字号 评论关闭

实现赋值操作符要注意的问题

* 赋值操作符实现的简例
CFoo & CFoo::operator=(const CFoo & rhs)

{

  if (this == &rhs)

    return *this;              // 防止自赋值


  // assign to all data members

  // ...


  return *this;                // 返回自身引用

}


* 要防止自身赋值
* 必须对每个成员赋值
* 增加新数据成员时,要同时更新赋值
* 子类赋值函数必须调用父类的赋值函数

derived& derived::operator=(const derived& rhs)

{

  if (this == &rhs) return *this;


  base::operator=(rhs);    // 调用this->base::operator=

  // 子类成员赋值...


  return *this;

}

但如果基类赋值运算符是编译器生成的,可这样实现derived::operator=:

derived& derived::operator=(const derived& rhs)

{

  if (this == &rhs) return *this;


  static_cast<base&>(*this) = rhs;      // 对*this的base部分

                                        // 调用operator=

  // ...

  return *this;

}

* 如果不会用到赋值操作,就声明一个私有赋值函数。

 

2010.12.14 补充: zy498420
指出成员赋值时须小心内存泄漏, 详见下面的评论.

 

抱歉!评论已关闭.