This crashes at runtime.
std::map<std::string, MyClass> myMap;
myValue = new MyClass();
myMap["myKey"] = *myValue;
I have 2 requirements:
- That instances of MyClass are held on the heap (hence use of new);
- That I be able to reference these via an associative array (hence use of std::Map).
Why can I not use the dereference operator succesfully in the example? How can I fulfill both at once?
PS. I’m using gcc.
If you lose the scope of
myValuethen it’s a memory leak. So it’s better to store theMyClass*in your map.In given example, also make sure you
deletethe element while erasing or removing from themap<>. You can use smart pointer (e.g.boost::shared_ptr) if you don’t want to worry about memory management.Also, from your given example I don’t know why it should crash while dereferencing
*myClass. Are you doing some weird stuff in copy constructorMyClass::MyClass(const MyClass&)?