In Win32 API programming it’s typical to use C structs with multiple fields. Usually only a couple of them have meaningful values and all others have to be zeroed out. This can be achieved in either of the two ways:
STRUCT theStruct;
memset( &theStruct, 0, sizeof( STRUCT ) );
or
STRUCT theStruct = {};
The second variant looks cleaner – it’s a one-liner, it doesn’t have any parameters that could be mistyped and lead to an error being planted.
Does it have any drawbacks compared to the first variant? Which variant to use and why?
Those two constructs a very different in their meaning. The first one uses a
memsetfunction, which is intended to set a buffer of memory to certain value. The second to initialize an object. Let me explain it with a bit of code:Lets assume you have a structure that has members only of POD types ("Plain Old Data" – see What are POD types in C++?)
In this case writing a
POD_OnlyStruct t = {}orPOD_OnlyStruct t; memset(&t, 0, sizeof t)doesn’t make much difference, as the only difference we have here is the alignment bytes being set to zero-value in case ofmemsetused. Since you don’t have access to those bytes normally, there’s no difference for you.On the other hand, since you’ve tagged your question as C++, let’s try another example, with member types different from POD:
In this case using an expression like
TestStruct t = {}is good, and using amemseton it will lead to crash. Here’s what happens if you usememset– an object of typeTestStructis created, thus creating an object of typestd::string, since it’s a member of our structure. Next,memsetsets the memory where the objectbwas located to certain value, say zero. Now, once our TestStruct object goes out of scope, it is going to be destroyed and when the turn comes to it’s memberstd::string byou’ll see a crash, as all of that object’s internal structures were ruined by thememset.So, the reality is, those things are very different, and although you sometimes need to
memseta whole structure to zeroes in certain cases, it’s always important to make sure you understand what you’re doing, and not make a mistake as in our second example.My vote – use
memseton objects only if it is required, and use the default initializationx = {}in all other cases.