If I write:
#include <map>
int main()
{
std::map<int, double> q;
q[3] += 4;
return 0;
}
Can I be assured q[3] is 4, and not that q[3] is 4 + (some random uninitialized garbage from memory)?
If I write:
#include <map>
int main()
{
std::map<int, double> q;
q[3] += 4;
return 0;
}
Can I be assured q[3] is 4, and not that q[3] is 4 + (some random uninitialized garbage from memory)?
Quoting from cppreference.com:
If an insertion is performed, the mapped value is value-initialized (default-constructed for class types, zero-initialized otherwise) and a reference to it is returned.
So you can count on the value being initialized to zero.
EDIT:
The quote above refers to the situation before C++11. The wording for C++11 and later is harder to understand, but here is what I think is the operative sentence:
When the default allocator is used, this results in the key being copy constructed from key and the mapped value being value-initialized.
The same parenthetical comment in the first quote also applies to the term "value-initialized" here (see the page on value initialization), so it will still zero initialize values of primitive types.
If q[3]
does not exist in the map, then that record is created for you and the value is initialised to zero.
Your code is safe.