2

I have something like this:

#include <iostream>
#include <map>

int main() {

    std::map<int, int*> mapaString;
    int* teste = mapaString[0];
    std::cout << teste << std::endl;
    if(!teste)
        mapaString[0] = new int(0);

    std::cout << mapaString[0] << std::endl;
    std::cout << mapaString[1] << std::endl;

    return 0;
}

In documentation at gcc and cpluplus.com it's just said that will be called the default constructor of the element, but when a pointer is declared without initializing it, its value will be undefined.

Is it guaranteed that the value returned will be a NULL pointer when calling subscript operator([]) when there is no mapped value assigned to the key and return type is a pointer?

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
coelhudo
  • 4,710
  • 7
  • 38
  • 57

2 Answers2

10

The "default constructors" of primitive types (including pointers) produce 0-filled memory, much like global variables.

Here is the relevant standard language (from dcl.init):

To default-initialize an object of type T means:

--if T is a non-POD class type (class), the default constructor for T is called (and the initialization is ill-formed if T has no acces- sible default constructor);

--if T is an array type, each element is default-initialized;

--otherwise, the storage for the object is zero-initialized.

...

7 An object whose initializer is an empty set of parentheses, i.e., (),
shall be default-initialized.

Also, from lib.map.access:

23.3.1.2 map element access [lib.map.access]

reference operator[](const key_type& x);

Returns: (*((insert(make_pair(x, T()))).first)).second.

-1

Just like any uninitialized variable, you cannot assume this will be initialized properly to value. It will depend on your build, release or debug, your compiler, your platform, etc. I would probably do this:

if(mapaString.find(key) == mapaString.end()) { mapaString[0] = 0; }

Then you can be sure the pointer for key was initialized to 0 / NULL.

terloon
  • 9
  • 1
  • Actually it will be value-initialized which will initialize basic types to null/0. Also doing the `find` and then `[]` does two searches on the `map` , which can be avoided. – Mark B Feb 09 '11 at 20:49
  • Ah. I've just been bitten by the uninitialized bug too many times, I thought it pertained to this as well. – terloon Feb 09 '11 at 21:44