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
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.
Try
myMap["dave"] = new People(....);
The new
will call the constructor, return a pointer and insert it into the map.
You need to be careful of memory leaks though. Use smart pointers to over come this problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With