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.