Re: zero memory
Christopher Pisz wrote:
What is the C++ way to zero out memory after calling operator new on a
struct?
A constructor is not possible in this case nor is a class, because the
people using my code c-stlye cast a pointer to the first member of the
struct to a pointer to the entrire struct later on in the code.
Note that there are a number of win32 structs that must be initialized
not only with zeros but with a member set to the size of the struct.
e.g. IMAGEHLP_SYMBOL64
The code below (checked on gcc) should automatically initialize an
entire struct to zeros and insert the right value in the "sizeofstruct"
member if it exists.
I did have a problem with visual studio on this technique a while back,
let's hope things have improved.
// This is used to initialize Win32 structs that contain a
// "sizeofstruct" structure.
struct NoMemb { char a[1]; };
struct Memb_SizeOfStruct { char a[2]; };
struct Memb_sizeofstruct { char a[3]; };
template <int w_val>
struct InitSizeOf;
template <>
struct InitSizeOf< sizeof( NoMemb ) >
{
template <typename U>
inline static void ObjInitSel( U & obj )
{
}
};
template <>
struct InitSizeOf< sizeof( Memb_SizeOfStruct ) >
{
template <typename U>
inline static void ObjInitSel( U & obj )
{
obj.SizeOfStruct = sizeof( obj );
}
};
template <>
struct InitSizeOf< sizeof( Memb_sizeofstruct ) >
{
template <typename U>
inline static void ObjInitSel( U & obj )
{
obj.sizeofstruct = sizeof( obj );
}
};
template <typename T>
struct InitObject
{
private:
struct xA {};
struct xB : xA {};
template <int w_size>
struct Detect
{
};
public:
template <typename U>
inline static Memb_sizeofstruct ObjInitSel(
U & obj, xB * b, Detect< sizeof(&U::sizeofstruct) > * = 0
);
template <typename U>
inline static Memb_SizeOfStruct ObjInitSel(
U & obj, xB * b, Detect< sizeof(&U::SizeOfStruct) > * = 0
);
template <typename U>
inline static NoMemb ObjInitSel( U & obj, xA * a );
inline static void ObjInit( T & obj )
{
typedef xB * bp;
InitSizeOf<sizeof( ObjInitSel(obj, bp()))>::ObjInitSel( obj );
}
};
struct InitStruct
{
template <typename T>
inline operator T ()
{
T obj = T();
InitObject<T>().ObjInit( obj );
return obj;
}
template <typename T>
inline operator T * ()
{
T * obj = new T();
InitObject<T>().ObjInit( * obj );
return obj;
}
};
/////////// test code
struct A
{
int a;
char x[10];
};
struct B
{
int SizeOfStruct;
char x[15];
};
struct C
{
int sizeofstruct;
char x[22];
};
B Bfoo()
{
return InitStruct();
}
C Cfoo()
{
return InitStruct();
}
A Afoo()
{
return InitStruct();
}
int main()
{
// make dynamically allocated version
C * c = InitStruct();
delete c;
Bfoo();
Cfoo();
Afoo();
}