c++ - Structure aggregate initialization with less clauses, why does it initialize everything? -



c++ - Structure aggregate initialization with less clauses, why does it initialize everything? -

if have mutual linux struct like:

struct sockaddr_in { sa_family_t sin_family; in_port_t sin_port; struct in_addr sin_addr; unsigned char __pad[__sock_size__ - sizeof(short int) - sizeof(unsigned short int) - sizeof(struct in_addr)]; }; #define sin_zero __pad

and perform aggregate initialization:

struct sockaddr_in my_addr = { 0 };

how come initializes every fellow member 0?

i mean: documentation says:

if number of initializer clauses less number of members or initializer clauses empty, remaining members initialized brace-or-equal initializers, if provided in class definition, , otherwise (since c++14) empty lists, performs value-initialization.

to create easy: why code print 0?

struct sockaddr_in my_addr = {2, 2}; // initialize sin_family , sin_port 2, else value-initialized my_addr = {0}; std::cout << my_addr.sin_port; // why 0?

this covered in draft c++14 standard section 8.5.4 list-initialization says:

list-initialization of object or reference of type t defined follows:

and includes:

if t aggregate, aggregate initialization performed (8.5.1).

and has next example:

struct s2 { int m1; double m2, m3; } s2 s21 = { 1, 2, 3.0 }; // ok s2 s22 { 1.0, 2, 3 }; // error: narrowing s2 s23 { }; // ok: default 0,0,0

and 8.5.1 aggregates says:

if there fewer initializer-clauses in list there members in aggregate, each fellow member not explicitly initialized shall initialized brace-or-equal-initializer or, if there no brace-or-equalinitializer, empty initializer list (8.5.4). [ example:

struct s { int a; const char* b; int c; int d = b[a]; }; s ss = { 1, "asdf" };

initializes ss.a 1, ss.b "asdf", ss.c value of look of form int{} (that is, 0)

note 8.5.4 different in c++11, says:

list-initialization of object or reference of type t defined follows:

if initializer list has no elements , t class type default constructor, object value-initialized.

otherwise, if t aggregate, aggregate initialization performed (8.5.1).

c++ initialization list-initialization

Comments

Popular posts from this blog

formatting - SAS SQL Datepart function returning odd values -

c++ - Apple Mach-O Linker Error(Duplicate Symbols For Architecture armv7) -

php - Yii 2: Unable to find a class into the extension 'yii2-admin' -