C ++ 03: default constructor for built-in types in std :: map

I always thought the following code

std::map<int, int> test; std::cout << test[0] << std::endl; 

will print a random value as it will create a uniform value inside the map. However, it turns out that the created int is always always initialized to zero. And standard built-in types are also initialized to zero under certain circumstances.

Question: when is zero initialization performed for standard types (int / char / float / double / size_t)? I am sure that if I declare int i; in the middle of nowhere, it will contain random data.

PS Question about the C ++ 03 standard. The reason for the question is that now I am not sure when I had to provide initialization for built-in types such as int / float / size_t or when they can be safely skipped.

+4
source share
5 answers

Standard containers ( map , vector , etc.) will always initialize their elements with a value.

Roughly speaking, initializing a value:

  • default-initialization if default constructor exists
  • zero initialization otherwise

(Some will say the best of both worlds)

The syntax is simple: T t = T(); would be value-initialize t (and T t{}; in C ++ 11).

When you use map<K,V>::operator[] , the "value" part of the pair is initialized with a value that gives 0 for the built-in type.

+9
source

I am sure that if I declare int i; nowhere in the middle will it contain random data.

No not always.

If you create an object of type POD, it will be unified:

 struct A { int iv; float fv; }; int main() { A a; // here the iv and fv are uninitialized } 

Once you add the constructor, they will be initialized:

 struct A { A(){} // iv and fv initialized to their default values int iv; float fv; }; int main() { A a; // here the iv and fv are initialized to their default values } 
+1
source

In particular, for the above case:

 std::map<int, int> test; std::cout << test[0] << std::endl; 

We use std::map::operator[];

Link http://www.cplusplus.com/reference/stl/map/operator [] /

For T & map :: operator [] (const key_type & x);

... If x does not match the key of any element in the container, the function inserts a new element with this key and returns a link to its displayed value. Please note that this always increases the size of the map by one, even if the element has no associated value (the element is built according to its default constructor) .

So test[0] leads to test[0] = int();

Here's a live example: http://ideone.com/8yYSk

Also read: std :: map default value for built-in type

+1
source

note that data types such as char, int, float are not initialized. but instead, in this particular case, it was initialized because it was used in the stl container class.

All objects of the stl container class are initialized.

0
source

The simplest solution is to simply create a template wrapper that will always be initialized.

-3
source

Source: https://habr.com/ru/post/1398802/


All Articles