可能重複:
Does std::list::remove method call destructor of each removed element?C++ - std :: list remove_if不釋放內存?
我有一個父類和子類的兩個孩子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;
}
酒吧看起來幾乎與Foo相同。我不認爲他們的行爲職能和他們的私人成員之間的差異會產生很大的差異(這也是一堆整數)。
我需要製作一份充滿Foos和酒吧的父母名單。我這樣做是爲了增加他們,並隨後將其刪除:
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庫進行此任務)
「確保我的程序不會泄漏內存」:始終使用智能指針容器而不是普通指針容器。 – ysdx 2012-01-17 00:06:02
@ysdx現在他只需要智能指針。聽起來像那份任務剛剛變得更加困難。 – pmr 2012-01-17 00:08:02
胡男孩。感謝您的幫助! – SpeedBurner 2012-01-17 00:20:10