Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code crash when storing objects in `std::map`

 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

like image 670
Sam Avatar asked May 22 '26 05:05

Sam


1 Answers

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.

like image 58
GManNickG Avatar answered May 24 '26 17:05

GManNickG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!