物探论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 1367|回复: 1

[Envi] C++库研究笔记——赋值操作符operator=的正确重载方式(...

[复制链接]
发表于 2013-8-12 11:30:27 | 显示全部楼层 |阅读模式

最终设计:
[cpp] view plaincopy
<span style="font-size:14px;">  MyClass& MyClass:perator=(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;  
  }</span>  


设计要求:
  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:perator=(const MyClass &rhs) {
    ...  // Do the assignment operation!


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

[cpp] view plaincopy
<span style="font-size:14px;">  MyClass& MyClass:perator=(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  
  }</span>  


但上述设计仍然不完整,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:
[cpp] view plaincopy
<span style="font-size:14px;">  MyClass& MyClass:perator=(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;  
  }</span>  

或者:
[cpp] view plaincopy
<span style="font-size:14px;">  MyClass& MyClass:perator=(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;  
  }</span>  

总之,重载操作符的三个准则
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

回复

使用道具 举报

发表于 2013-11-20 21:29:37 | 显示全部楼层
顶一下
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑屋|物探论坛 ( 鄂ICP备12002012号 微信号:iwutan )

GMT+8, 2024-3-29 09:54 , Processed in 0.066596 second(s), 15 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表