Effective C++ 11. Handle assignment to self in operator=
来源:互联网 发布:网络测试工程师 编辑:程序博客网 时间:2024/06/06 13:25
class Widget { ...private: Bitmap *pb;};
不安全, 受自赋值影响
Widget& Widget::operator=(const Widget& rhs) { delete pb; // unsafe, should avoid assignment to self pb = new Bitmap(*rhs.pb); return *this;}
还是不安全,如果申请内存失败将丢失原信息
Widget& Widget::operator=(const Widget& rhs) { if (this == &rhs) return *this; delete pb; pb = new Bitmap(*rhs.pb); return *this;}
改进后的两种方法
I.
Widget& Widget::operator=(const Widget& rhs) { Bitmap *pOrig = pb; pb = new Bitmap(*rhs.pb); if (pb == NULL) //申请内存失败, 赋回原值 pb = pOrig; else delete pOrig; return *this;}
II.
class Widget { ... void swap(Widget& rhs); ...};
Widget& Widget::operator= (const Widget& rhs) { Widget temp(rhs); swap(tmp); return *this;}
Widget& Widget::operator=(const Widget rhs) { swap(rhs); return *this;}
阅读全文
0 0
- Effective C++ 11. Handle assignment to self in operator=
- Item11: Handle assignment to self in operator=
- 【条款11】Handle assignment to self in operator=
- 条款11:在operator=中处理“自我赋值”(Handle assignment to self in operator=.)
- [翻译] Effective C++, 3rd Edition, Item 11: 在 operator= 中处理 assignment to self(自赋值)
- Effective C++, 3rd Edition, Item 11: 在 operator= 中处理 assignment to self(自赋值)
- effective c++ item11在 operator= 中处理 assignment to self(自赋值)
- Effective C++——operator =
- 【effective c++】条款10:令operator=返回一个reference to *this
- 《Effective C++》学习笔记条款10 令operator= 返回一个reference to *this
- Effective C++——》条款10:令operator=返回一个reference to *this
- Effective C++:条款10:令operator=返回一个reference to *this。
- 读书笔记《Effective C++》条款10:令operator=返回一个reference to *this
- C++之令operator=返回一个reference to *this(10)---《Effective C++》
- [C++]copy constructor and copy assignment operator
- how to handle the c string and comments in flex
- effective c++ 令operator=返回一个reference to *this
- Copy Construct && Copy assignment(Operator =)
- ubuntu安装
- 分享一个工具类---SharedPreferences
- 多台服务器共享session问题浅析
- Mongo数据库
- oracle 12c误删pdb数据文件导致整个数据库无法打开问题
- Effective C++ 11. Handle assignment to self in operator=
- 设计模式_命令模式(21)
- koa入门教程
- Spring Cloud分布式微服务云架构服务组件
- day15MySQL数据库操作
- ARM和x86比较
- moni1
- java编程思想学习笔记(一)——java类与c++类的区别
- IDEA 快捷键集合