Quick C++ stack vs heap memory

In the following scenario:

class SubObject
{
public:
list<string> myStringList;

SubObject();
~SubObject();
}

class MainObject
{
public:
map<int, SubObject> myMap;

MainObject();
~MainObject();

}


MainObject *mainObjectPtr;
main(int argc, char *argv[]))
{

mainObjectPtr = new MainObject();

...

}


My question is regards to memory and my use of new (and non use). My application memory continuously grows during the life of the program (I never delete the mainObjectPtr). The system constantly adds items into myMap. The system also removes items from myMap. Remove by calling myMap.erase(key value). Will the system ever be able to access the areas of memory that I erased from the map? Or is this memory never accessible again because I am not using new/delete?

My breakdown of my problem may not be clear, but I would appreciate any input. Thanks
uhm, what?
myMap.erase should use delete. so when removing an object from the map the destructor is called.
Therefore you should be able to access that areas again.

It's different if you only add items to the map.
Then of course the memory will rise up and up.
You can simply test that by printing something in the edstructor of SubObjects

~SubObject(){ std::cout << "SubObject: destroyed" << std::endl;" }

If that's still not enough you can use a static variable to count the amount of SubObject's
1
2
3
4
5
6
7
8
9
class SubObject
{
public:
    list<string> myStringList;
    static int count = 0; // only with c++11, otherwise you have to initialize it outside the class

    SubObject()  {count++; /* stuff */ }
    ~SubObject() {count--; /* stuff */ }
}
Last edited on
I added the output statement to the constructor. It does get called. But my question has to do with the memory size of:

mainObjectPtr = new MainObject();

Has the available memory for the system increased now that I have cleared the elements in myMap? Or will this memory only be availble again once I call delete on mainObjectPtr?
Topic archived. No new replies allowed.