gan_ gan_ - 10 months ago 69
C++ Question

Why does std::vector zero initilize its memory?

I recently noticed that

does clear it's memory with zeros after allocating.

I have created similar containers before (although not
compliant) and I never needed to explicitly zero the memory before creating new items.

I can't see a reason to do that and I was just wondering why.

To illustrate :

struct S {
int s[128];

bool vector_zeroed() {
std::vector<S> c;
while(c.size() < 1000) {

bool zeroed = true;
for(const auto& s : c) {
for(int i : s.s) {
zeroed &= i == 0;
return zeroed;

bool array_zeroed() {
bool zeroed = true;
auto *s = new S[1000];
for(int k = 0; k != 1000; ++k) {
for(int i : s[k].s) {
zeroed &= i == 0;
delete[] s;
return zeroed;

seems to always return

I am obviously missing something here but i don't know what.

Answer Source

CPP reference documentation:

the below overloaded constructors zeroes out elements of non-class types such as int, which is different from the behavior of new[] , which leaves them uninitialized.

explicit vector( size_type count );   (since C++11)  (until C++14)
explicit vector( size_type count, const Allocator& alloc = Allocator() );
(since C++14)