I always thought that following code
std::map<int, int> test;
std::cout << test[0] << std::endl;
would print random value, because it would create unitialized value within map. However, it turns out that created int is actually always initialized to zero AND standard builtin types are also zero-initialized in certain circumstances.
The question is : when zero-initialziation is performed for standard types (int/char/float/double/size_t)? I'm pretty sure that if I declare int i;
in the middle of nowhere, it will contain random data.
P.S. The question is about C++03 standard. The reason for the question is that now I'm no longer certain when I have to provide initialization for builtin types like int/float/size_t or when it can be safely omitted.
Standard containers (
map
,vector
, etc...) will always value-initialize their elements.Roughly speaking, value-initialization is:
(Some would say, the best of both worlds)
The syntax is simple:
T t = T();
will value-initializet
(andT t{};
in C++11).When you use
map<K,V>::operator[]
, the "value" part of the pair is value-initialized, which for a built-in type yields0
.In particular for the above case :
We are using
std::map::operator[];
Refering 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 that key and returns a reference to its mapped value. Notice that this always increases the map size by one, even if no mapped value is assigned to the element (the element is constructed using its default constructor).
So,
test[0]
leades totest[0] = int();
Live example here: http://ideone.com/8yYSk
Also read : std::map default value for build-in type
please note that Data types like char,int,float are not initialized. but instead in this particular case it was initialized because it was used in stl container class.
All stl container class objects are initialized.
The simplest solution is to simply create a template wrapper that will always be initialized.
No, not always.
If you create an object of POD type, then it will be unitialized :
As soon as you add a constructor, they become initialized :