在經歷Effective C++(Scott Meyers)期間,我遇到以下代碼,作者使用它來說明如何在將數據成員從一個對象複製到另一個時處理異常。處理複製賦值運算符中的異常(C++)
class Bitmap { ... };
class Widget {
...
private:
Bitmap *pb; // ptr to a heap-allocated object
};
Widget& Widget::operator=(const Widget& rhs)
{
Bitmap *pOrig = pb; // remember original pb
pb = new Bitmap(*rhs.pb); // make pb point to a copy of *pb
delete pOrig; // delete the original pb
return *this;
}
如果「新位圖」引發異常,pb將保持不變。但是,通過刪除 pOrig,pb點已被釋放的內存。這不危險嗎?它是如何比任何下面的代碼
Widget& Widget::operator=(const Widget& rhs)
{
if (this == &rhs) return *this; // identity test: if a self-assignment,
// do nothing
delete pb;
pb = new Bitmap(*rhs.pb);
return *this;
}
這(他聲稱)是不好的,因爲當「新位圖」產生的異常更好(或者因爲沒有用於分配或因爲位圖的拷貝構造函數拋出一個內存不足) ,Widget最終將持有一個指向已刪除位圖的指針
我檢查了勘誤表,但未發現此示例。我錯過了明顯的東西嗎?另外,有人可以提出一個更好的方法來處理這個異常?
明白了,謝謝。 – Sam 2012-03-26 02:24:23