Effective C++ Item11 Note

来源:互联网 发布:macbook视频制作软件 编辑:程序博客网 时间:2024/05/20 00:35
//Effective C++ Item11 在operator=中处理自我赋值#include<iostream>#include<cstring>using namespace std;class Bitmap{};class Widget{public:Widget& operator=(const Widget& rhs){//*this和rhs有可能是同一个对象,此时pb将错误地指向一个已被删除的对象,因此需要做证同测试if (this == &rhs)return *this;//考虑异常安全性,如果new Bitmap导致异常(不论是因为分配时内存不足或因为Bitmap的copy构造函数抛出异常),pb将指向一块被删除的Bitmap//因此应该在new Bitmap成功之后再delete原来指向的内存Bitmap* pOrig = pb;pb = new Bitmap(*rhs.pb);delete pOrig;return *this;}private:Bitmap*pb;};

0 0
原创粉丝点击