Mox Mox - 1 year ago 77
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;
if(myMap[0] == NULL) {// true or false?

will the if statement evaluate to true?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download