In Win32 programming a handful of POD structs is used. Those structs often need to be zeroed out before usage.
This can be done by calling memset()
/
I always use:
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)};
Many Win32 structs require you to set the size in a first member.
In Win32, ZeroMemory
is just a Macro around RtlZeroRemory
, which is a macro to memset. So, I don't think it makes a difference.
WinBase.h
:
\#define ZeroMemory RtlZeroMemory"
WinNT.h
:
\#define RtlZeroMemory(Destination,Length) memset((Destination),0,(Length))
If your code will serve as an example to countless Visual Basic developers who are likely to not notice or understand the C++ = {}
construct, ZeroMemory is a good way to make the C++ code look more like pseudocode and minimize the incidence of subtle, hair-ripping initialization bugs.
That's the concern that the MSDN article authors faced, which then explains why ZeroMemory shows up in so much code (even C++ code).
On the other hand, if the purpose of your C++ code is to make a working product, rather than to teach the world, using the elegant and expressive power of the C++ language is a great idea.
The only reason to prefer memset
/ZeroMemory
for this kind of initialization is if WinAPI functions require/expect the memory to be initialized that way, i.e. if WinAPI functions expect their zeros to be physical zeros - values with all-zero bit patterns.
Keep in mind that the difference between a representation of a zero value of some type and physical all-zero-bit pattern depends on the compiler implementation, not on OS. In theory, a Windows compiler can use non-zero bit patterns to represent zero values of various types. Like, a null pointer might be represented by non-zero physical value in some imaginary C or C++ compiler for Windows. (Not that anyone would actually do that, of course).
The end result is identical (so long as you assume that 0 is always represented by all-zero-bits), so it's largely a matter of style. Personally, I prefer value initialisation, since it is simpler and doesn't require function calls.
Incidentally, you must initialise at least one member:
STRUCT theStruct = {0};
Omitting the 0
is allowed by some C compilers, but not by the C standard. C++ allows the omission, but I prefer to just always use the 0
.
in c++11:
struct A {
int x = 10;
int y = 100;
int z = 0;
};
old style c++
struct A {
int x;
int y;
int z;
A() : x( 10 ), y( 100 ), z( 0 ) {} //constructor
};