开发者

Initializing the first element in a struct

I do a lot of Win32 programming in C++ and many Win32 structures have a 'size' (often called cbSize or length) member as the first element which needs to be set before the relevant API call can be made. For example:

WINDOWPLACEMENT wp;
wp.length = sizeof(WINDOWPLACEMENT);
GetWindowPlacement(hWnd, &wp);

Now, I think it is good practice to initialize structure members to zero which I can do with:

WINDOWPLACEMENT wp = { };

or

WINDOWPLACEMENT wp = { 0 };
开发者_开发知识库

However, what happens to the other members of the struct if I initialize the first member like this:

WINDOWPLACEMENT wp = { sizeof(WINDOWPLACEMENT) };

Are they automatically initialized to zero? Or does it depend on which compiler I'm using and whether it's a debug build or not?


Yes, they're automatically initialized to zero.

8.5.1/7:

If there are fewer initializers in the list than there are members in the aggregate, then each member not explicitly initialized shall be value-initialized (8.5). [Example:

struct S { int a; char* b; int c; };
S ss = { 1, "asdf" };

initializes ss.a with 1, ss.b with "asdf", and ss.c with the value of an expression of the form int(), that is, 0. ]


If you are sure the size is the first element, this will be ok. Any members that don't get a value in the initializer will be zeroed.


This:

WINDOWPLACEMENT wp = { X };

Will initialize all remaining members to 0 (assuming POD).

See: 8.5.1 Aggregates [dcl.init.aggr] Paragraph: 7:

7 If there are fewer initializer-clauses in the list than there are members in the aggregate, then each member not explicitly initialized shall be value-initialized (8.5).

[ Example:

   struct S { int a; char* b; int c; };
   S ss = { 1, "asdf" };

initializes ss.a with 1, ss.b with "asdf", and ss.c with the value of an expression of the form int(), that is, 0. —end example ]

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜