c++ - Will {0, 0} initialize array in the struct? -
in code, 100 items of c.b
initialized zero?
struct { int b[100]; int d; }; c = {0, 0};
it seems work, memory have been empty in advance.
the line
a c = {0, 0};
performs value initialization of aggregate a
. according standard, braces can omitted aggregate initialization:
8.5.1 aggregates[dcl.init.aggr]/12
braces can elided in initializer-list follows. if initializer-list begins left brace, succeeding comma-separated list of initializer-clauses initializes members of subaggregate; erroneous there more initializer-clauses members. if, however, initializer-list sub- aggregate not begin left brace, enough initializer-clauses list taken initialize members of subaggregate; remaining initializer-clauses left initialize next member of aggregate of current subaggregate member.
[example:
float y[4][3] = { { 1, 3, 5 }, { 2, 4, 6 }, { 3, 5, 7 }, };
is completely-braced initialization: 1, 3, , 5 initialize first row of array y[0], namely y[0][0], y[0][1], , y[0][2]. likewise next 2 lines initialize y[1] , y[2]. initializer ends , therefore y[3]'s elements initialized if explicitly initialized expression of form float(), is, initialized 0.0. in following example, braces in initializer-list elided; initializer-list has same effect completely-braced initializer-list of above example,
float y[4][3] = { 1, 3, 5, 2, 4, 6, 3, 5, 7 };
the initializer y begins left brace, 1 y[0] not, therefore 3 elements list used. likewise next 3 taken successively y[1] , y[2]. — end example ]
next
8.5.1 aggregates[dcl.init.aggr]/7
if there fewer initializer-clauses in list there members in aggregate, each member not explicitly initialized shall initialized brace-or-equal-initializer or, if there no brace-or-equal- initializer, empty initializer list.
in case, mean first 0
assigned b[0]
, second 0
assigned b[1]
. according 8.5.1/7, rest of elements value-initialized.
however, clarity in case, should use a c = {{0}, 0};
, or, better
a c{}; // or c = {};
the thing worries me bit g++ warning (-wextra
):
warning: missing initializer member 'main()::a::d' [-wmissing-field-initializers] c {0,0};
but according interpretation of standard above, should ok , d
should have been initialized. tested placement new
, , result expected
#include <iostream> int main() { struct { int b[100]; int d;}; memory{}; memory.d = 42; std::cout << memory.d << std::endl; // let's place @ location of memory a* foo = new (&memory) a{0,0}; // line below outputs 0, d erased; not case if a* foo = new (&memory) a; std::cout << memory.d << std::endl; // outputs 0 }
Comments
Post a Comment