我正在阅读这本书,但我不明白两段代码之间的区别。
class Bitmap{...};
class Widget
{
...
private:
Bitmap* m_pb;
};
Widget& Widget::operator=(const Widget& rhs)
{
if (this == &rhs)
{
return *this; // if a self-assignment, do nothing
}
delete pb;
pb = new Bitmap(*rhs.m_pb);
return *this;
}
迈耶斯先生说:
如果“new Bitmap”表达式产生异常,Widget 将最终持有指向已删除 Bitmap 的指针。
这是否意味着pd指针指向 NULL?
Widget& Widget::operator=(const Widget& rhs)
{
Bitmap* temp = pb;
pb = new Bitmap(*rhs.pb);
delete temp;
return *this;
}
迈耶斯先生说:
现在,如果“new Bitmap”抛出异常,pb 指针保持不变。
据我所知,temp指针指向与pb指针相同的内存地址。如果 "new" 抛出异常,pb将指向 NULL,下一句将删除 Bitmap。那是对的吗?我看不出这些实现之间的区别。
提前致谢。