C ++中的{0}是什么意思? [英] What Does {0} Mean in C++?

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

问题描述

{0} 用于在C ++中初始化对象时,是什么意思?我在任何地方找不到对 {0} 的任何引用,并且因为大括号谷歌搜索没有帮助。



示例代码:

  SHELLEXECUTEINFO sexi = {0}; 
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);如果没有它,上面的代码将在运行时崩溃。

$

 

解决方案

这里发生的情况称为聚合初始化。下面是ISO规范第8.5.1节中聚合的(缩写)定义:


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


,使用 {0} 初始化一个这样的聚合基本上是一个窍门, 0 整个事情。这是因为在使用聚合初始化时,不必指定所有成员,并且规范要求将所有未指定的成员默认初始化,这意味着设置为 0







$ b b

如果列表中的初始化器比
聚合中的成员少,那么每个未被
初始化的成员将被
默认初始化。
示例:

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

使用<$ c初始化 ss.a $ c> 1
asdf int()形式的
表达式的值来定义 ss.c
0


主题这里


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

Example code:

SHELLEXECUTEINFO sexi = {0};
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.

解决方案

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.

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" };

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

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

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