gpt4 book ai didi

c++ - 大括号括起来的初始化列表

转载 作者:行者123 更新时间:2023-11-30 00:59:22 25 4
gpt4 key购买 nike

假设我有一个类似于这个的对象:

struct MenuDef
{
int titleResourceId;

struct MenuItemDef {
char* name;
int value;
SomeFunctionPtr someFactory;
} menuItems[10];
};

初始化是这样的:

const MenuDef m = {
1,
{
{
"zero",
0,
(SomeFunctionPtr) & MenuButton::factory,
},
{
"one",
1,
(SomeFunctionPtr) & MenuButton::factory,
},
{
"two",
2,
(SomeFunctionPtr) & MenuButton::factory,
},
}
};

假设 m.menuItems[3].someFactory == 0 是否安全?

例如在这样的循环中:

for ( int i = 0; m.menuItems[i].someFactory != 0; ++i)

或者为了安全起见,我是否必须手动插入最后一个元素来标记数组结束?

...
{
"two",
2,
(SomeFunctionPtr) & MenuButton::factory,
},
{
"",
0,
(SomeFunctionPtr) 0,
},
...

最佳答案

根据 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).

提醒一下:

To value-initialize an object of type T means:

  • if T is a class type (clause 9) with a user-declared constructor (12.1), then the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);
  • if T is a non-union class type without a user-declared constructor, then every non-static data member and base-class component of T is value-initialized;
  • if T is an array type, then each element is value-initialized;
  • otherwise, the object is zero-initialized

关于c++ - 大括号括起来的初始化列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4539563/

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