gan_ gan_ - 1 month ago 5
C++ Question

Why does std::vector zero initilize its memory?

I recently noticed that

std::vector
does clear it's memory with zeros after allocating.

I have created similar containers before (although not
std
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) {
c.emplace_back();
}

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;
}


vector_zeroed()
seems to always return
true
while
array_zeroed()
returns
false
.

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

Answer

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)

http://en.cppreference.com/w/cpp/container/vector/vector