初始化对象时,{0}是什么意思? [英] What does {0} mean when initializing an object?

查看:228
本文介绍了初始化对象时,{0}是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 {0} 初始化对象是什么意思?我在任何地方都找不到对 {0} 的引用,由于花括号,Google搜索无济于事。

When {0} is used to initialize an object, what does it mean? I can't find any references to {0} anywhere, and because of the curly braces Google searches are not helpful.

示例代码:

SHELLEXECUTEINFO sexi = {0}; // what does this do?
sexi.cbSize = sizeof(SHELLEXECUTEINFO);
sexi.hwnd = NULL;
sexi.fMask = SEE_MASK_NOCLOSEPROCESS;
sexi.lpFile = lpFile.c_str();
sexi.lpParameters = args;
sexi.nShow = nShow;

if(ShellExecuteEx(&sexi))
{
    DWORD wait = WaitForSingleObject(sexi.hProcess, INFINITE);
    if(wait == WAIT_OBJECT_0)
        GetExitCodeProcess(sexi.hProcess, &returnCode);
}

没有它,以上代码将在运行时崩溃。

Without it, the above code will crash on runtime.

推荐答案

这里发生的事情称为聚集初始化。这是来自ISO规范8.5.1节的聚合的(缩写)定义:

What's happening here is called aggregate initialization. Here is the (abbreviated) definition of an aggregate from section 8.5.1 of the ISO spec:


聚合是数组或类没有用户声明的构造函数,没有私有或受保护的非静态数据成员,没有基类,也没有虚拟函数。

An aggregate is an array or a class with no user-declared constructors, no private or protected non-static data members, no base classes, and no virtual functions.

现在,使用 {0} 初始化这样的聚合基本上是把 0 整件事的窍门。这是因为在使用聚合初始化时,您不必指定所有成员,并且该规范要求所有未指定的成员都被默认初始化,这意味着设置为 0 用于简单类型。

Now, using {0} to initialize an aggregate like this is basically a trick to 0 the entire thing. This is because when using aggregate initialization you don't have to specify all the members and the spec requires that all unspecified members be default initialized, which means set to 0 for simple types.

以下是规范中的相关报价:

Here is the relevant quote from the spec:


如果列表中的初始值设定项少于
集合中的成员数,则未明确初始化的
成员均应进行
默认初始化。
示例:

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

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

用<$ c初始化 ss.a $ c> 1 , ss.b
asdf ,和 ss.c ,其值的形式为 int()
表达式,即
0

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.

您可以在此找到完整的规格主题此处

You can find the complete spec on this topic here

这篇关于初始化对象时,{0}是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆