gpt4 book ai didi

c++ - 初始化结构中的第一个元素

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:15:03 26 4
gpt4 key购买 nike

我用 C++ 进行了很多 Win32 编程,许多 Win32 结构都有一个“大小”(通常称为 cbSizelength)成员作为需要在可以进行相关的 API 调用之前设置。例如:

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

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

WINDOWPLACEMENT wp = { };

WINDOWPLACEMENT wp = { 0 };

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

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:

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

关于c++ - 初始化结构中的第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5330672/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com