Mox Mox - 28 days ago 14
C++ Question

Is inserted value of pointer type by operator[] in map always NULL?

What is the expected behaviour for the following code,

#include <map>
...
std::map<int, A *> myMap;
myMap[0];
if(myMap[0] == NULL) {// true or false?
}


will the if statement evaluate to true?

Answer

The inserted value will be initialized to a null pointer.

std::map::operator[] will perform an insertion if key does not exist; the mapped value will be value-initialized, for pointer type it's zero-initialization, which results in a null pointer.

BTW: Better to use nullptr (since C++11) instead of NULL.