关于C#:初始化结构中的第一个元素


Initializing the first element in a struct

我用C语言进行了很多Win32编程,许多Win32结构都有一个'size'(通常称为cbSizelength)成员作为第一个元素,需要在进行相关API调用之前进行设置。例如:

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

现在,我认为将结构成员初始化为零是一种很好的做法,我可以使用:

1
WINDOWPLACEMENT wp = { };

1
WINDOWPLACEMENT wp = { 0 };

但是,如果我像这样初始化第一个成员,该结构的其他成员会怎样:

1
WINDOWPLACEMENT wp = { sizeof(WINDOWPLACEMENT) };

它们是否自动初始化为零?还是取决于我使用的是哪个编译器以及它是否为调试版本?


是的,它们会自动初始化为零。

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:

1
2
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. ]


如果您确定尺寸是第一个元素,则可以。在初始化器中未获取值的所有成员将被清零。


此:

1
WINDOWPLACEMENT wp = { X };

将所有剩余成员初始化为0(假设POD)。

请参阅:8.5.1聚合[dcl.init.aggr]段落: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:

1
2
   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 ]