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-initialize t
(and T 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 yields 0
.
I'm pretty sure that if I declare int i; in the middle of nowhere, it will contain random data.
No, not always.
If you create an object of POD type, then it will be unitialized :
struct A
{
int iv;
float fv;
};
int main()
{
A a; // here the iv and fv are uninitialized
}
As soon as you add a constructor, they become 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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With