Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle a map with pointers?

Tags:

c++

pointers

map

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

like image 700
user1356190 Avatar asked Apr 26 '12 12:04

user1356190


2 Answers

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.

like image 155
Flexo Avatar answered Sep 29 '22 16:09

Flexo


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.

like image 44
Ed Heal Avatar answered Sep 29 '22 14:09

Ed Heal