tags:

views:

443

answers:

1
 typedef std::map<int, MyObject*> MyMap;
 MyMap* myMap = new MyMap;
 // ...
 myMap->insert( MyMap::value_type( 0, objectOfType_MyObject ) );

Why does my code crash with a stack trace going down to

 std::less<int>::operator()

?

I understand that if I use a custom key class that I must provide a comparator, but this is an int.

I've never used maps before and it's probably a dumb question but I've been stuck on this for ages now.

Thanks

+6  A: 

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.

GMan
Very good answer; In the last case, he might also need to define a copy constructor for MyObject.
Indeera
My problem was that I am not .clear() 'ing the map on initialising my class. (Even though it is size 0). I am storing Obj-C objects
Sam