I have a class in C++ with the following member:
map< someEnum, vector<SomeObject*>* > someMap
So I have a map that gives me a vector of objects for each enumeration I have. For the life of me, I cannot understand how C++ is initializing these objects. Does it deep initialize them by default? If not, what do I need to do?
I'm getting segmentation faults no matter how I try to do this (and I have tried everything), so I'm guessing I'm missing something conceptually.
map< someEnum, vector<SomeObject*> > someMap
as well and that didn't work as well. In this case, does C++ deep-initialize the vector?
The rule is: If an STL container contains pointers to objects, it it does not create objects on heap and assign them to these pointers. If, however, it contains objects themselves, it does call the default constructor of each contained object and thus initialises them.
What you have here is a map containing pointers (no matter what kind). So do not expect the map to make these pointers to point to memory.
It looks like the map gives you a pointer to a vector of objects. If you try to use the map via
mymap[MY_ENUM]->push_back(whatever);
before you initialize, you'll get a segfault. You either need to initialize the vector first
mymap[MY_ENUM] = new vector<SomeObject*>;
or, much better, just make the map give you a plain ol' vector
map <someEnum, vector<SomeObject*> > mymap;
When you first call mymap[MY_ENUM], the vector will be default-initialized (with size zero). Is the problem that you're trying to use the entries of the vector before you enlarge it, e.g.,
mymap[MY_ENUM][2] = whatever;
You still need to use push_back or resize, or something that gives you some space.
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