arataj
arataj

Reputation: 373

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

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


    in = new RandomAccessFile(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?

Upvotes: 3

Views: 187

Answers (1)

Karel Petranek
Karel Petranek

Reputation: 15154

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.

Upvotes: 11

Related Questions