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


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

* 赋值操作符实现的简例
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 指出成员赋值时须小心内存泄漏, 详见下面的评论.

 

评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值