Home > OS >  std::vector zeroing out trivial types
std::vector zeroing out trivial types

Time:12-24

The author of chrono claims here that if you have a vector of chrono::seconds, it does not initialize by default. I'm wondering how that's accurate, e.g. if I initialize a vector of a struct that wraps an int, e.g. the assertion never triggers below. Does this have to do with zero init pages allocated or does the standard guarantee this?

#include <vector>
#include <cassert>

struct X {
    int y;
};

int main() { 
    std::vector<X> vec(10);
    for (auto &el : vec) { 
        assert(el.y == 0);
    }
}

CodePudding user response:

If you read e.g. this std::vector constructor reference, the definition

std::vector<X> vec(10);

is number 4 in that reference list (since C 11), which uses default insertion for the elements.

And default insertion does (by default) value initialization which for an aggregate like your structure does aggregate initialization which in turn will make you int member

copy-initialized from an empty initializer list

Which will set it to zero.

There are a lot of steps to go through, but it all ends up with the well-defined behavior of initializing all y members to zero.

CodePudding user response:

Looks like he meant array instead of vector, because vector elements are always initialized.

std::array<second, 100> arr1;                        // not initialized
std::array<second, 100> arr2{};                      // zero initialized
std::unique_ptr<second[]> arr3{ new second[100] };   // not initialized
std::unique_ptr<second[]> arr4{ new second[100]{} }; // zero initialized
std::vector<second> vec(100);                        // zero initialized
  •  Tags:  
  • c
  • Related