用3种方法在 operator= 中处理“自我赋值”
来源:互联网 发布:智慧城市大数据概念股 编辑:程序博客网 时间:2024/04/28 09:56
假设你建立一个class 用来保存一个指针指向一块动态分配的位图。
1 class Bitmap {......};2 class Widget{3 ...4 private:5 Bitmap* pb ;6 };
1 Widget& Widget::operator= (const Widget& rhs)2 {3 delete pb;4 pb = new Bitmap(*rhs.pb);5 return *this;6 }
上面是一份不安全的 operator= 实现版本,因为 operator= 函数内的*this 和 rhs 有可能是同一个对象。欲阻止这种错误有三种方法。
方法一:传统的方法
1 Widget& Widget::operator= (const Widget& rhs)2 {3 if( this == rhs ) return *this;4 delete pb;5 pb = new Bitmap(*rhs.pb);6 return *this;7 }
方法二:
1 Widget& Widget::operator= (const Widget& rhs)2 {3 Bitmap* pOrig = pb ;4 5 pb = new Bitmap(*rhs.pb);6 delete pOrig ;7 return *this;8 }
方法三:所谓的copy and swap 技术
1 Widget& Widget::operator= (const Widget& rhs)2 {3 Widget temp( rhs ) ;4 swap(temp);5 6 return *this;7 }
0 0
- 用3种方法在 operator= 中处理“自我赋值”
- 在operator=中处理自我赋值
- 条款11: 在operator= 中处理"自我赋值"
- 条款11:在operator= 中处理“自我赋值”
- 条款11: 在operator= 中处理"自我赋值"
- item11: 在operator=中处理自我赋值
- 条款11:在operator = 中处理"自我赋值"
- 条款11:在operator=中处理“自我赋值”
- tip11:在operator=中处理自我赋值
- 条款11:在operator=中处理”自我赋值“
- 总结条款:11在operator=中处理“自我赋值”
- 第11条: 在 operator= 中处理“自我赋值”
- 条款11 在operator=中处理“自我赋值”
- 条款11:在operator=中处理“自我赋值”
- 条款11 在operator=中处理“自我赋值“
- (9)在 operator=中处理自我赋值
- 条款11 在operator=中处理“自我赋值”
- 条款11:在operator=中处理“自我赋值
- Sudoku Solver
- Command 模式
- 完整java开发中JDBC连接数据库代码和步骤
- 复制构造函数 与 赋值操作函数
- 关于 const 成员函数
- 用3种方法在 operator= 中处理“自我赋值”
- View.setTag()的作用
- 多平台适配的代码设计
- Android中为APP创建快捷方式的原理(自己的理解)
- JavaScript性能优化小知识总结
- 使用java.util.Timer来周期性的执行制定的任务
- 新建线程与UI线程间的通信
- pdf转换word转换器下载
- Android中解析XML的方法