1

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)?

Carbon
  • 3,828
  • 3
  • 24
  • 51
  • 1
    downvoted because any serious doc for `map::operator[]` should cover this – 463035818_is_not_an_ai Feb 01 '18 at 16:32
  • 4
    @tobi303: It's buried quite deep though. – Bathsheba Feb 01 '18 at 16:33
  • [the documentation](http://en.cppreference.com/w/cpp/container/map/operator_at) says *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.* Seems pretty clear to me. – Kevin Feb 01 '18 at 16:34
  • Even more than that, std::vector(100) would be a vector of a hundred zeroes. – bipll Feb 01 '18 at 16:35
  • Is that still true for C++11? – Carbon Feb 01 '18 at 16:35
  • @Bathsheba If you look into example for http://en.cppreference.com/w/cpp/container/map/operator_at it explicitly mentions that, I doubt it is buried – Slava Feb 01 '18 at 16:39
  • 1
    @Slava: Let's resist this becoming some kind of bragging contest. Answering questions well is the best way to show off, should you feel the need to. – Bathsheba Feb 01 '18 at 16:41

2 Answers2

6

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.

Fred Larson
  • 60,987
  • 18
  • 112
  • 174
4

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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483