Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C++ deep-initialize class members?

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.


I should note that I tried to use:
map< someEnum, vector<SomeObject*> > someMap

as well and that didn't work as well. In this case, does C++ deep-initialize the vector?

like image 448
Yuval Adam Avatar asked Sep 10 '26 13:09

Yuval Adam


2 Answers

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.

like image 197
Frederick The Fool Avatar answered Sep 12 '26 01:09

Frederick The Fool


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.

like image 31
Jesse Beder Avatar answered Sep 12 '26 03:09

Jesse Beder