c++自我赋值问题
ringa_lee
ringa_lee 2017-04-17 13:45:27
0
2
396

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;
 }
 
ringa_lee
ringa_lee

ringa_lee

reply all(2)
左手右手慢动作

The second way of writing will cause memory leaks when copying itself

Ty80

The role of pb is to bind between referenced values ​​and memory objects on the heap. If you want to access objects on the heap, you need to operate through pb.

See the picture above. According to the example you gave, you instructed pb to point to a new heap memory address, but you did not delete it before, which will cause a memory leak.

An example of a leak

class BigData{
private:
    int data[1024*1024*128];
};

int main(){
    BigData *p = 0;
    for (int i = 0; i < 4; ++i) {
        p = new BigData();
    }
    return 0;
}



BigData是一个大小为128MB的对象,创建了4个,没释放,则可以看到程序运行期内存一直增长。
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template