Re: zero memory
ajk wrote:
On Thu, 5 Apr 2007 16:49:52 -0500, "Christopher Pisz"
<someone@somewhere.net> 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.
so memset() should do the trick
"the c++ way" would be to have a class and to initialize it in the
ctor
e.g.
class CMYSTRUCT : public MYSTRUCT
{
public:
CMYSTRUCT() {
memset(&overlapped,0,sizeof(overlapped)); mamajama=0; next=NULL; }
You really want to avoid using memset. It will bite you one day.
Try this:
CMYSTRUCT() : MYSTRUCT( MYSTRUCT() ) {}
But your problem does not end there :-(
};
Foo()
{
PMYSTRUCT = new CMYSTRUCT;
In this case, you're calling new on CMYSTRUCT and I expect that you'll
call delete on a MYSTRUCT. That's undefined. Bad things will happen if
don't modify that habbit.
}
or make the MYSTRUCT a class
MYSTRUCT is a class.
I just thought of yet another way - this one will create a default
constructed or zero initialized POD object depending on what type of
pointer you're trying to assign it to.
struct InitObj
{
template <typename T>
operator T * ()
{
return new T();
}
};
// usage - template automagically figures out which type to new
PMYSTRUCT * mys = InitObj();
int * z = InitObj();
Note the lack of a memset call and note that the code will work for POD
types as well as non POD types.