为什么将一个对象指针传递给一个方法,它在哪里被删除,不同于直接删除对象? [英] Why passing an object pointer to a method, where it is deleted, is different from deleting the object directly?

查看:153
本文介绍了为什么将一个对象指针传递给一个方法,它在哪里被删除,不同于直接删除对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

导致一个块泄漏的代码如下:

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



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

其中 RandomAccessFile 是类 string 字段, delObject()是一个静态方法,如下所示:

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



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

泄漏的块是 string

如果我用直接 delete delObject $ c>:

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?

推荐答案

我只能猜测,但似乎你忘了一个对象类中的虚拟析构函数。因此,不会调用RandomAccessFile析构函数导致其属性泄漏。

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.

这篇关于为什么将一个对象指针传递给一个方法,它在哪里被删除,不同于直接删除对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆