So, I’m using a std::map as an associative array. The map is declared as such:
std::map<int, CustomClass*> CustomContainer;
Later on, I use the CustomContainer object as an associative array, e.g.,
CustomClass* pClass = CustomContainer[ID]
Josuttis states:
If you use a key as the index, for which no element yet exists, a new element get inserted into the map automatically. The value of the new element is initialized by the default constructor of its type. Thus, to use this feature you can’t use a value type that has no default constructor
The value of the map is of type CustomClass*. Will the value default to NULL, or is it undefined? (I think that it wouldn’t, as “pointer” isn’t a fundamental data type). I would think it would also rely somewhat on the constructor and the behavior there as well…. thoughts???
The only constructor of CustomClass looks like this:
CustomClass::CustomClass(ClassA param1, ClassB param2, ClassC param3, ClassD param4)
:privateClassA(param1),
privateClassB(param2),
privateClassC(param3),
privateClassD(param4)
{
}
Thanks much!
An uninitialized local pointer variable or field will have undefined value, just like uninitialized
int(or, in general, POD-type) local variable or field would. However, this has nothing to do with question at hand.When you use
operator[]on map, and it creates a new entry, it is default-initialized. This means null pointer value for pointers (and 0 forints, and so on). It would never be undefined.If you actually need to check if there is an item with such key in the map or not, and do not want new entries, use
find()member function, and compare the returned iterator toend().