I’m having trouble with std::list and memory leaks:
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;
}
With just the PackOfObjs declared I have 2 memory leaks already, and they go away if I remove the std::list, and they increase by 1 for each address I add to the list.
I tried clearing the list and some codes of removing all the objs pointed to before clearing, but at least 2 memory leaks still persist.
Since I didn’t use any new (not even on the elements I add), I’m guessing the list itself creates some variables and don’t delete them, how can I fix this?
When
_CrtDumpMemoryLeaks()runs, all the objects allocated inside ofmainstill exist. You are calling_CrtDumpMemoryLeaks()too early. Instead, try this:I seem to remember that the recommended way of calling
_CrtDumpMemoryLeaksis at the destructor of a global object. That may still be too early for other global objects, but at least then all objects created inside ofmainwill have been destroyed already.