Why are the entries of this STL card not initialized in GCC 4.5.1?

Here is a snippet of code.

std::map<double, double> temp; temp[0] = .1; cout << temp[1] << endl; // result varies based on compiler 

I compile using GCC version 4.4.1 and I get the value 0 from temp[1] as I expect. My employee compiles in GCC version 4.5.1. In debug mode (with the -g flag) it gets 1000 . When compiling the release mode ( -O2 ), it gets 0 .

My thought is that this is the type of problem that usually occurs with uninitialized variables, except that maps should call the default constructor for their elements based on this question and some others like it.

In addition, the Josuttis C ++ Standard Library claims to

If you use the key as an index for which an element does not yet exist, the new element gets automatically inserted into the map. The value of the new element is initialized by the default constructor of its type.

Why are elements in the map not initialized in GCC 4.5.1 in debug mode? Don't I understand what others said about this behavior correctly? Is building new elements by default something that is not necessarily part of the standard? Or could it be a compiler error?

+7
source share
3 answers

As you might expect, a piece of code is a simplified version of what is actually happening. It turns out that the find command is used on the map, so map.find(1)->second is called essentially instead of map[1] . This explains the behavior of undefined.

+1
source

It should work the way you say (type 0 ), but in fact in g ++ 4.5.2 it prints 0 with -g , -O2 or both. If it does not print 0, it is almost certainly a library error (or your co-worker program already has undefined behavior, in which case all bets are disabled (TM)).

+4
source

Yes, it will be initialized to 0 in accordance with the C ++ standard.

Link:

C ++ 03 Standard:

23.3.1.2 access to the map element [lib.map.access]

T& operator[](const key_type& x);

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

T() default - initializes the object. Although the default values ​​for the variables are listed in the section:

C ++ 03 Standard 8.5 / 5:

In default-initialize, an object of type T means:
- if T is a non-POD class type (section 9), the default constructor for T is called (and initialization is poorly formed if T does not have an available default constructor); - if T is an array type, each element is initialized by default;
- , otherwise the object is initialized to zero.

The latter case applies to your code here.

+2
source

All Articles