问题描述
当 {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
主题
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:
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:
You can find the complete spec on this topic here
这篇关于C ++中的{0}是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!