问题代码: class Bitmap{}; class Widget{ public: ... Widget& operator=(const Widget& rhs){ delete hBitmap; hBitmap_ = new Bitmap(*rhs.hBitmap_); return *this; } private: Bitmap* hBitmap_; }; 修改后: //改进一步 Widget& Widget::operator=(const Widget& rhs){ if(this == &rhs){ //增加了判断条件 return *this; } delete hBitmap_; hBitmap_ = new Bitmap(*rhs.hBitmap_); // throw possibel exception? return *this; } //改进二步 Widget& Widget::operator=(const Widget& rhs){ Bitmap* holdBitmap_ = hBitmap_; hBitmap_ = new Bitmap(*rhs.hBitmap_); delete holdBitmap_; return *this; } //改进三步 class Widget{ public: Widget& operator=(const Widget& rhs){ Widget tempt(rhs); //make a source copy swap(rhs); return *this; } ... private: void swap(const Widget& rhs); //交换两个Widget对象数据 ... }; //改进四步 class Widget{ public: Widget& operator=(Widget rhs){ swap(rhs); return *this; } .... private: void swap(const Widget& rhs); ... };