开发者

Why passing an object pointer to a method, where it is deleted, is different from deleting the object directly?

开发者 https://www.devze.com 2023-03-20 22:49 出处:网络
The code causing a leak of one block is as follows: in = new RandomAccessF开发者_运维百科ile(fileName, \"r\");

The code causing a leak of one block is as follows:


    in = new RandomAccessF开发者_运维百科ile(fileName, "r");
    in->close();
    Mem::delObject(in);

where RandomAccessFile is the class with the string field, and delObject() is a static method as follows:


    void Mem::delObject(Object* object) {
        delete object;
    }

The leaked block is that of string.

If I replace the method delObject with a direct delete:


    in = new RandomAccessFile(fileName, "r");
    in->close();
    delete(in);

the leak is gone. If the method is not replaced, but removed instead:


    in = new RandomAccessFile(fileName, "r");
    in->close();
    // Mem::delObject(in);
    // delete(in);

there are two leaked blocks. I guess the field and the object that contained it.

So: why these two ways of deleting an object behave differently?


I can only guess but it seems you forgot a virtual destructor in Object class. Thus the RandomAccessFile destructor won't be called causing a leak of its properties.

0

精彩评论

暂无评论...
验证码 换一张
取 消