我遇到了 std::list 和内存泄漏问题:
class AbstractObject
{
public:
virtual void Say() = 0;
}
class RealObject : public AbstractObject
{
public:
virtual void Say() { cout << "Real Obj Says..." << endl; } //Do I need the "virtual" keyword here too?
}
class AnotherRealObject : public AbstractObject
{
public:
virtual void Say() { cout << "Another Real Obj Says..." << endl; } //Do I need the "virtual" keyword here too?
}
class PackOfObjects
{
public:
std::list<AbstractObject*> objects; //list of pointers because it doesn't let me create a list of an abstract class
void Say()
{
for(std::list<AbstractObject*>::iterator obj = objects.begin(); obj != objects.end(); obj++)
{
(*obj)->Say();
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
PackOfObjs myObjs;
RealObject objA;
myObjs.objects.push_back(&objA); //This adds 1 memory leak
AnotherRealObject objB;
myObjs.objects.push_back(&objB); //This adds another 1 memory leak
_gettch();
_CrtDumpMemoryLeaks();
return 0;
}
仅声明了 PackOfObjs,我已经有 2 个内存泄漏,如果我删除 std::list,它们就会消失,并且对于我添加到列表中的每个地址,它们都会增加 1。我尝试清除列表和一些在清除之前删除所有指向的 obj 的代码,但至少 2 个内存泄漏仍然存在。
由于我没有使用任何新的(甚至没有在我添加的元素上),我猜测列表本身会创建一些变量并且不删除它们,我该如何解决这个问题?