gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 01:00:38 25 4
gpt4 key购买 nike

<分区>

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 库用于此作业)

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com