A wide range of structures is used in Win32 programming. Many times only some of their fields are used and all the other fields are set to zero. For example:
STARTUPINFO startupInfo; // has more than 10 member variables ZeroMemory( &startupInfo, sizeof( startupInfo ) ); //zero out startupInfo.cb = sizeof( startupInfo ); //setting size is required according to MSDN startupInfo.dwFlags = STARTF_FORCEOFFFEEDBACK; //Now call CreateProcess() passing the startupInfo into it
I want to stop copy-pasting such code and instead use an abstraction that would care about zeroing and setting parameters. Let’s presume I only need the struct initialized as in example, and no other tuning is ever needed. Is the following a good solution? What are possible problems?
class CStartupInfo : public STARTUPINFO { public: CStartupInfo() { ZeroMemory( this, sizeof( STARTUPINFO ) ); cb = sizeof( STARTUPINFO ); dwFlags = STARTF_FORCEOFFFEEDBACK; } };
I’m in particular concerned about the ZeroMemory() call – looks like I fully control the code and the class has no vtable and calling ZeroMemory() this way is safe and there’s no big difference between the two code snippets except that the latter provides an abstraction. Are there any caveats?
I think this is a fine way to make such structures more bulletproof. I’m not sure why others seem to not like the technique. I use it occasionally, but not as often as I otherwise might because it doesn’t seem to be very well liked by coworkers for some reason.
I don’t see it used in published material very often – the only one I could find in a quick Google right now is an article by Paul DiLascia in MSJ August 1997 (http://www.microsoft.com/MSJ/0897/C0897.aspx):
I can’t think of much in the way of drawbacks (except the lack of acceptance). If anyone else can point to something more concrete, I’d appreciate it.