Spoon said:
Hello everyone,
Consider a class with many integer members.
I want to set every bit in all members to 0 in the constructor.
struct Foo
{
Foo() { memset(this, 0, sizeof *this); }
int a, b, c, d, e, f, g, h, i, j, k;
};
Is it safe to use memset this way in this situation?
This was done quite a bit in C. I was working on some code in C converting
it to C++. One thing I wanted to do was to add a class with a constructor
to structure. Which broke. And I couldn't figure out why. Then I finally
tracked it down to a memset type of issue( it was different, but similar).
Consdier you class.
struct Foo
{
Foo() { memset( this, 0, sizeof *this ); }
int a,b,c,de,f,g,j,i,j,k;
};
Later you decide to store a name in this so you add a std::string.
struct Foo
{
Foo() { memset( this, 0, sizeof *this ); }
int a,b,c,de,f,g,j,i,j,k;
std::string Name;
};
Now Name won't work. It'll cause memory segmentation faults and such when
you try to access it. Can you figure out why? Because all the ponters
stored in Name when it has been constructed have been set to 0, effectively
becoming NULL pointers (on some systems) losing the memory they pointed to,
along with other data they need.
memset of a structure or class is a BAD thing.