I have a container object which contains float*.

struct MyCon{
    MyCon(){
        matA = new float[10];
        matB = new float[10];
    }
    float *matA;
    float *matB;
}

And, I am storing pointers to MyCon objects in a std::map.

map<string, MyCon*> myCon_map;
myCon_map.insert(pair<string,MyCon*>(string("str"), new MyCon()));

Once I am finished with myCon_map, how do I return all memory?

You need a destructor for MyCon that frees the memory. Something like this should work.

~MyCon()
{
    delete [] matA
    delete [] matB
}

Okay, I added the destructor. But, when does the MyCon destructor get called?

Can I just let the std::map (which contains only pointers to MyCon objects) go out of scope? Will I need to manually call the destructor for each object? The MyCon objects have newed members on the heap, but they as well have been newed onto the heap.

As the MyCon objects have all been allocated on the heap with new, you should probably iterate through the map and delete all of the MyCon elements before the std::map drops out of scope!

So iterate through the map, delete each MyCon pointer and perhaps use map.erase to remove each pair from the map as you go (probably not necessary, but couldn't hurt!):

const map<string, MyCon*>::iterator end = myConMap.end();
map<string, MyCon*>::iterator it = myConMap.begin();
for(;it!=end; ++it)
{
    MyCon *con = it->second;
    delete con;
    myConMap.erase(it);
}
Comments
Thank you!
This article has been dead for over six months. Start a new discussion instead.