1

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?

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
Mox
  • 2,355
  • 2
  • 26
  • 42
  • `NULL` should read `nullptr` perhaps? Also why not use smart pointers – Ed Heal Nov 10 '16 at 03:22
  • That code does nothing as it doesn't compile. Throw in the correct headers, as `map` could be someone's home made map. – PaulMcKenzie Nov 10 '16 at 03:23
  • @EdHeal, its some legacy code in company and we are using legacy compiler.. xD – Mox Nov 10 '16 at 03:27
  • 1
    If you want to avoid entering invalid numbers into the map, use `find()` for searching, and `insert()` instead of `[]` for making new entry. – Saurav Sahu Nov 10 '16 at 03:51
  • @SauravSahu, I agree with that. it will improve the robustness of the code, but due to very poor SE practice in office, I am not allowed to change code that doesn't belong to me. – Mox Nov 10 '16 at 03:54

1 Answers1

5

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.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • it is due to some constraint that I am working with in my company. we are still using C++98 standard. a lot of features from the latest C++ are missing. e.g smart ptr ... > – Mox Nov 10 '16 at 03:24
  • Thanks for the answer, I will accept asap =) – Mox Nov 10 '16 at 03:31