Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behavior of calling operator [] when no mapped value is assigned to the key

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?

like image 324
coelhudo Avatar asked Jan 27 '26 20:01

coelhudo


1 Answers

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.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!