effective第11个条款举的这个例子:
Widget& Widget::operator=(const Widget& rhs) //一份不安全的operator=实现版本
{
delete pb;
pb = new Bitmap(*rhs.pb);
return *this;
}
像上面这样写,自我赋值肯定会出现问题,但是为什么要先释放掉pb呢?为什么不直接像下面这样重赋值呢?
Widget& Widget::operator=(const Widget& rhs) //一份不安全的operator=实现版本
{
pb = new Bitmap(*rhs.pb);
return *this;
}
Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
第二种写法当自我复制时会造成内存泄漏