This code works (compiles & runs) for me:
#include <map>
class MyObject
{ };
int main(void)
{
typedef std::map<int, MyObject*> MyMap;
MyMap *myMap = new MyMap;
MyObject *obj = new MyObject;
myMap->insert(MyMap::value_type(0, obj));
delete obj;
delete myMap;
}
So the problem lies in the details (// ...
or what MyObject
can do) or elsewhere. You can probably fix things up a bit to help. Try to stack allocate things when you can. Do you actually need a pointer to a map? I suggest you don't:
#include <map>
class MyObject
{ };
int main(void)
{
typedef std::map<int, MyObject*> MyMap;
MyMap myMap;
MyObject *obj = new MyObject;
myMap.insert(MyMap::value_type(0, obj));
delete obj;
}
And do you actually need to store pointers to object, or objects?
#include <map>
class MyObject
{ };
int main(void)
{
typedef std::map<int, MyObject> MyMap;
MyMap myMap;
myMap.insert(MyMap::value_type(0, MyObject()));
}
Much smaller, and almost impossible to get memory leaks. If you do need to store pointers, for polymorphic behavior, check out boost::ptr_container library, which has a map adapter that stores pointers.