How to handle a map with pointers?

c++, dictionary, pointers

Solution

Given the map:

map<string, People*> myMap;

`operator[]` won't create new `People`, it will be creating `People*`, i.e. pointers that don't point to anything.

The simplest solution is to make your map really contain people, not pointers, e.g.:

map<string, People> myMap;

then the memory management is all handled for you, using `operator[]` will construct new people as needed.

Problem

Consider I have a class names People. I'm storing pointers to these people in a map ``` map<string, People*> myMap; ``` To create new People I use the maps [] operator. ``` myMap["dave"]->sayHello(); ``` But this gives me a segmentation errors and it doesn't even call the constructor of the People class. I also tried ``` myMap.insert( std::make_pair( "dave", new People() )); ``` But that didn't change anything, the Constructor still isn't called and the program shuts down processing this code with an segmentation error. How do I access and manipulate a map with pointers in them? Why isn't the above working, I get no compile time errors or warnings. Any insight much appreciated, thank you

Original source