Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the default allocator zeroize int?

Tags:

c++

stl

allocator

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.

like image 289
peter Avatar asked Mar 06 '12 13:03

peter


2 Answers

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().

like image 95
Luchian Grigore Avatar answered Oct 31 '22 22:10

Luchian Grigore


The standard guarantees that objects created as a result of using the subscript operator are default constructed. Whether the default constructor for any particular class zeroes the members you expect to be zeroed is up to theclass. For classes without constructors members are default constructed and default construction fundamental types amounts to setting the to their version of "zero".

Note, this has nothing to do with allocators! ... and it is pretty safe to assume that tbe allocators leave the memory untouched, except possibly dedicated debugging allocators (or allocators written by people tricked into thinking that zeroing the memory might be Good Thing rather than a device hiding bugs). ... and the debugging allocator wouldn't zero the memory but fill it with a recognizable pattern ( e.g. resulting in 0xdeadbeef when viewed in hexadecimal).

like image 6
Dietmar Kühl Avatar answered Oct 31 '22 21:10

Dietmar Kühl