C ++析构函数内存泄漏 [英] C++ destructor memory leak

查看:214
本文介绍了C ++析构函数内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正确处理析构函数的相对简单的问题...

Relatively simple question about handling destructors properly...

首先我有一个类似这样的类:

First I've got a class that's something like this:

class Foo {
public:
    ReleaseObjects() {
        for (std::map<size_t, Object*>::iterator iter = objects.begin(); iter != objects.end(); iter++) {
            delete (*iter).second;
        }
        objects.clear();
    }

private:
    std::map<size_t,Object*> objects;
}

因此,函数只是删除使用'new'创建的对象。 Problem是一个Object类:

So the function simply deletes the objects, which were created using 'new'. Problem is an Object class:

class Bar : public Object {
public:
    Bar() {
        baz = new Baz();
    }

    ~Bar() { delete baz; }
private:
    Baz* baz;
}



如果我添加一个类型Baz对象到Foo,然后尝试ReleaseObjects ),我得到一个内存泄漏(valgrind)。问题指向baz泄漏,我想这意味着bar中的析构函数从来没有调用?所以我想知道的是如何调用Bar析构函数时试图销毁该对象(我不能改变Bar类,但我可以改变Foo)。

If I add a type Baz object to Foo, and then try to ReleaseObjects(), I get a memory leak (valgrind). The issue points to baz being leaked, and I guess that means the destructor in bar is never called? So what I'd like to know is how to call the Bar destructor when trying to destroy that object (I can't alter the Bar class, but I can alter Foo).

编辑:
糟糕,对于语法错误,抱歉。无论如何,感谢所有的答复,傻我忘了在我的Baz类实现一个适当的析构函数!哦,Baz实际上是一个模板类,但我认为Baz是与我的问题无关的,这个问题是Bar的析构函数不被调用...好吧,我错了,问题是在Baz毕竟。但是再次感谢,我想我从这里想出来了!

Oops, sorry for the syntax errors. Anyways, thanks for all the replies, silly me forgot to implement a proper destructor in my Baz class! Oh, and Baz is actually a template class, but I figured Baz was sort of irrelevant to my question, and that the problem was the destructor in Bar not being called... well, I was wrong, problem is in Baz after all. But thanks again, I think I got it figured out from here!

推荐答案

你必须确保你的析构函数virtual,以便调用适当的派生析构函数。

You've got to make sure that your destructor is virtual so that the proper derived destructor is called.

class Object {
 . . .
 virtual ~Object()
 . . .
};

这篇关于C ++析构函数内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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