C++ 拷貝構造的一個小陷阱

Widget& Widget::opterator=(const Widget& rhs)

{

       delete pb;

       pb = new Bitmap(*rhs.pb);

       return *this;

假設這裏的rhs 就是this,delete 後 給拷貝構造函數傳參,會異常。

因此,我們這樣寫。

Widget& Widget::opterator=(const Widget& rhs)

{

      if(&rhs == this)

      {

            return *this;

      }

       delete pb;

       pb = new Bitmap(*rhs.pb);

       return *this;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章