Zeroing the structure in the constructor

Win32 programming uses a wide range of structures. Many times, only some of their fields are used, and all other fields are 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 copying such code and use an abstraction instead, which will take care of zeroing and settings. Suppose I only need a structure initialized, as in the example, and no other configuration is required. Is the following a good solution? What are the possible problems?

class CStartupInfo : public STARTUPINFO {
public:
   CStartupInfo()
   {
       ZeroMemory( this, sizeof( STARTUPINFO ) );
       cb = sizeof( STARTUPINFO );
       dwFlags = STARTF_FORCEOFFFEEDBACK;
   }
};

ZeroMemory() - , , vtable ZeroMemory() , , , , . - ?

+3
8

, . , , , . , , , .

, - , Google , - MSJ August 1997 (http://www.microsoft.com/MSJ/0897/C0897.aspx):

CRebarInfo CRebarBandInfo ++ C structs REBARINFO REBARBANDINFO, , cbSize .

( ). - , .

+1

, :

STARTUPINFO startup_info = { sizeof(STARTUPINFO), 0 };
startup_info.dwFlags = STARTF_FORCEOFFFEEDBACK;

, - . , cb ( /) . , :

STARTUPINFO startup_info = { 0 };
startup_info.cb = sizeof(STARTUPINFO);
startup_info.dwFlags = STARTF_FORCEOFFFEEDBACK;

, ATL/WTL, , , .

, , , , .

+5

, ?

STARTUPINFO CreateStartupInfo( DWORD flags ) {
  STARTUPINFO info;
  ZeroMemory(&info, sizeof(info));
  info.cb = sizeof(STARTUPINFO);
  info.dwFlags = flags;
  return info;
}

, . (), . , , , .

, , . RAII. , .

+4

tonj, , intellisense, :

template <typename T>
T& ZeroInit(T & data) 
{ 
  ZeroMemory(&data, sizeof(data)); 
  return data;
}

template <typename T>
T& ZeroInitCB(T & data) 
{ 
  ZeroMemory(&data, sizeof(data)); 
  data.cb = sizeof(data); 
  return data;
}

selfzero < > :

STARTUPINFO si;
ZeroInitCB(si);

- - intellisense;)

T & , .

+3

:

template <class T>
class selfzero : public T
{
public:
    selfzero() {
        ZeroMemory( this, sizeof( selfzero<T> ));
    };
};

:

{
    selfzero<STARTUPINFO> si;
}

: , vtable vtable , .

+2

TonJ:

template <class T>
class selfzero : public T
{
public:
    selfzero() {
        ZeroMemory( (T*) this, sizeof( T ));
    };
};

Zeroes T, selfdata. , vtables . T , ((T *) ) vtables.

+1

trival, , . , . , "" , .

0

, , , :

class zbool {
private:
  bool value;
public:
  zbool(const bool value) { ... }
  operator bool() { ... }
  // ... code skipped
};

:

struct MyStruct {
  zbool deleted;
};

, , .

-1

Source: https://habr.com/ru/post/1706867/


All Articles