有什么理由更喜欢memset / ZeroMemory来为WinAPI结构初始化值? [英] Any reason to prefer memset/ZeroMemory to value initialization for WinAPI structs?
问题描述
在Win32编程中,使用了一些POD结构。那些结构通常在使用前需要清零。
In Win32 programming a handful of POD structs is used. Those structs often need to be zeroed out before usage.
这可以通过调用 memset()
/ ZeroMemory()
This can be done by calling memset()
/ZeroMemory()
STRUCT theStruct;
ZeroMemory( &theStruct, sizeof( theStruct ) );
或通过值初始化:
STRUCT theStruct = {};
- 对填充进行不同处理
- 对非POD成员变量进行不同处理
在Win32中使用POD结构时,它们看起来是等效的。
in case of POD structs used in Win32 they look equivalent.
在任何情况下 memset()$ c $应该使用c> /
ZeroMemory()
代替Win32 POD结构的值初始化吗?
Are there any cases when memset()
/ZeroMemory()
should be used instead of value initialization with Win32 POD structs?
推荐答案
我一直使用:
STRUCT theStruct = {}; // for C++, in C use {0}
它更短,更标准,因此更优雅,并且我并不在乎理论上的差异。我们在这里讨论具体操作系统的代码。
It's shorter, standard, therefore more elegant, and I don't really care about the theoretical differences. We are talking about code for a concrete OS here.
另一个优点是,您也可以像这样在第一个成员中立即设置结构大小:
Another advantage is you can also immediately set the struct size in the first member like this:
STRUCT theStruct = {sizeof(STRUCT)};
许多Win32结构要求您在第一个成员中设置大小。
Many Win32 structs require you to set the size in a first member.
这篇关于有什么理由更喜欢memset / ZeroMemory来为WinAPI结构初始化值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!