Home > Mobile >  Initialize a std::vector of structures to zero
Initialize a std::vector of structures to zero

Time:01-19

I am guaranteed to initialize a vector of struct with each element initialized to zero with that code ?

#include <vector>

struct A {
    int a, b;
    float f;
};

int main()
{
    // 100 A's initialized to zero (a=0, b=0, f=0.0)
    // std::vector<A> my_vector(100, {}); does not compile
    std::vector<A> my_vector(100, A{});
}

CodePudding user response:

Short answer : Yes

To know how refer below : when you write

std::vector<A> my_vector(...)

you are doing value initialization if the parentheses are empty, or direct initialization if non-empty.

and when you write A{} you are doing list initialization which implies value initialization if the braces are empty, or aggregate initialization if the initialized object is an aggregate.

as your parentheses are non-empty so below code

std::vector<A> my_vector(100, A{});

is interpreted as

std::vector<A> my_vector(/*created vector of 100 elements */ 100, /* by list  Initialization of struct with default values*/A{});

As A{} is empty in this case you are doing value initialization which is leading to zero_initialization as

  1. As part of value-initialization sequence for non-class types and for members of value-initialized class types that have no constructors, including value initialization of elements of aggregates for which no initializers are provided.

CodePudding user response:

Yes it is guaranteed since A{} is value initialization and from cppreference:

Zero initialization is performed in the following situations:

  • As part of value-initialization sequence for non-class types and for members of value-initialized class types that have no constructors, including value initialization of elements of aggregates for which no initializers are provided.

You can also use:

std::vector<A> my_vector(100, {0,0,0}); 

CodePudding user response:

Yes, you are guaranteed to have zero initialization with that code

  •  Tags:  
  • Related