C++库研究笔记——赋值操作符operator=的正确重载方式(三个准则)

C++ Operator Overloading Guidelines

最终设计:

  MyClass& MyClass::operator=(const MyClass &rhs) {
    // Check for self-assignment!
    if (this == &rhs)      // Same object?
      return *this;        // Yes, so skip assignment, and just return *this.

    ... // Deallocate, allocate new space, copy values...
    return *this;
  }



设计要求:
  a, b, c, d, e;


  a = b = c = d = e = 42;
This is interpreted by the compiler as:
  a = (b = (c = (d = (e = 42))));
  MyClass a, b, c;
  ...
  (a = b) = c;  // What??
  // Take a const-reference to the right-hand side of the assignment.
  // Return a non-const reference to the left-hand side.
//对应上条
  MyClass& MyClass::operator=(const MyClass &rhs) {
    ...  // Do the assignment operation!


    return *this;  // Return a reference to myself.
  }

  MyClass& MyClass::operator=(const MyClass &rhs) {
    // 1.  Deallocate any memory that MyClass is using internally
    // 2.  Allocate some memory to hold the contents of rhs
    // 3.  Copy the values from rhs into this instance
    // 4.  Return *this
  }


但上述设计仍然不完整,a=a会出现什么情况? 当然还要考虑性能问题

  MyClass mc;
  ...
  mc = mc;     // BLAMMO.
 CHECK FOR SELF-ASSIGNMENT.


所以正确且安全的设计如下:So, the correct and safe version of the MyClass assignment operator would be this:
  MyClass& MyClass::operator=(const MyClass &rhs) {
    // Check for self-assignment!
    if (this == &rhs)      // Same object?
      return *this;        // Yes, so skip assignment, and just return *this.

    ... // Deallocate, allocate new space, copy values...
    return *this;
  }

或者:

  MyClass& MyClass::operator=(const MyClass &rhs) {
    // Only do assignment if RHS is a different object from this.
    if (this != &rhs) {
      ... // Deallocate, allocate new space, copy values...
    }
    return *this;
  }

总之,重载操作符的三个准则
1.右端值要为const 类型(不想改变他的值)Take a const-reference for the argument (the right-hand side of the assignment).
2.要返回一个引用,以便于实现(a=b=c…… (Do this by returning *this.)

3.检查是否为自我赋值Check for self-assignment, by comparing the pointers (this to &rhs).

-----------------------------------------------------

类似的,我们可以设计这样的运等符(数据传输)
a<<(b<<c) 与上文一样的
当然如果我们只允许a<<b非连锁的操作(指a<<b<<c不允许),我们可以抛弃掉规则2

  void MyClass::operator=(const MyClass &rhs) {
    // Only do assignment if RHS is a different object from this.
    if (this != &rhs) {
      ... // Deallocate, allocate new space, copy values...
    }
    return *this;
  }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值