Search code examples
c++stlallocator

Does the default allocator zeroize int?


When using STL containers, I am not sure whether an int allocated by the default allocator has been zeroized. The following code indicates 'yes' to the question:

#include <map>
#include <iostream>

int main() {
  using namespace std;
  map<int, int> m;
  cout << m[1234] << endl;
}

Since no document has confirmed this, I don't dare to take it for granted.


Solution

  • You'll see, inside the implementation of std::map::operator[], if the element is not found at the index, a new one is inserted and returned:

    ReturnValue = this->insert(where, make_pair(key_value, mapped_type()));
    

    where mapped_type is the second type, in your case int. So yes, it is default-initialized to 0, since it's inserted as mapped_type().