C++ - std::list remove_if 不释放内存?

标签 c++ list memory-leaks subclass std

<分区>

Possible Duplicate:
Does std::list::remove method call destructor of each removed element?

我有一个父类并将两个子类 Foo 和 Bar 子类化。类声明看起来像这样:

class Parent {
    public:
        virtual void action()=0;
        std::string getName() {return name;}
        Parent(std::string name): name(name) {}
        virtual ~Parent() {}
    private:
        std::string name;
}
class Foo {
    public:
        virtual void action(); //Declared somewhere else.
        Foo(int a, int b, unsigned long c, std::string name): Parent(name),a(a),b(b),c(c) {}
        virtual ~Foo() {}
    private:
        int a,b;
        unsigned long c;
}

Bar 看起来与 Foo 非常相似。我不认为它们的 Action 函数和它们的私有(private)成员之间的差异会产生很大的不同(它也是一堆整数)。

我需要列出一个充满 Foos 和 Bars 的 Parents 列表。我这样做是为了添加它们并随后删除它们:

std::list<Parent *> pList;
pList.push_back(new Foo(1,2,3,"Thing"));
removeFromList(&pList, "Thing");

其中removeFromList定义如下:

// Binary predicate struct, find objects with matching name.
struct NameMatch : public std::binary_function< Parent*, std::string, bool > {
     bool operator () (Parent* p, const std::string name) const {
         return (p->getName()==name);
     }
};

/* Removes a named object from the list of Foos. 
   Does nothing if a matching name can't be found. */
void removeFromList(std::list<Parent *> *pList, std::string name) {
    pList->remove_if(std::bind2nd(NameMatch(),name));
}

但是,一旦我之后退出程序,Valgrind 会报告有内存泄漏,其中 main.cpp 引用的行是在列表上完成的 push_back 操作:

==14230== 949 (520 direct, 429 indirect) bytes in 13 blocks are definitely lost in loss record 52 of 61
==14230==    at 0x4C28B35: operator new(unsigned long) (vg_replace_malloc.c:261)
==14230==    by 0x4026C8: main (main.cpp:93)
==14230== 
==14230== 5,970 (960 direct, 5,010 indirect) bytes in 30 blocks are definitely lost in loss record 60 of 61
==14230==    at 0x4C28B35: operator new(unsigned long) (vg_replace_malloc.c:261)
==14230==    by 0x40296A: main (main.cpp:112)

这是否意味着列表的 remove_if 函数没有释放内存,还是我在其他地方犯了错误?我如何确保我的程序不会因使用这些类而泄漏内存?第二组眼睛会很有帮助。

提前致谢! (哦,仅供引用,我不能将 Boost 库用于此作业)

最佳答案

您的列表包含指向对象的指针。您只是删除了指针,但没有释放它指向的内存(销毁对象)。在删除指针之前,您需要在指针上调用 delete。这意味着 list::remove_if 不能完成这里的工作。您需要遍历列表,删除每个符合条件的对象并使用迭代器调用 list::erase

这里没有简单的出路。你需要运行时多态性,所以你需要指针,你不能使用 boost::shared_ptr。也许你可以作弊并使用 std::shared_ptrstd::unique_ptr ;)

关于C++ - std::list remove_if 不释放内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8887993/

相关文章:

android - 内存泄漏和 OutOfMemoryError

c++ - STL 是否有办法在调用 less than 之前应用一个函数?

c++ - 函数类型引用函数类型: undefined reference

c++ - 模板函数指针参数与构造函数参数

c++ - 来自 TBB 节点的异步输入/输出和非均匀输出

jquery - CSS 列表项不显示在彼此下方

list - 为什么 `Nil` 被定义为 `case object`

c - 单链表的段错误

javascript - 这段nodejs代码是循环引用吗?

multithreading - 来自线程的同步事件 - 内存泄漏