lallous wrote:
Hello,
Given:
class X
{
int x, y; // and many many more....
X()
{
memset((void*)this, 0, sizeof(X));
}
};
Is this a good way to clear *all* members of a class?
This is definitely inviting trouble.
You are making the assumption that -
sizeof (X) = sizeof(x) + sizeof(y) ( sum of individual
variables ), which is not correct .
What if the class got a virtual members ,
and hence a VTBL (virtual table) is constructed.
You are going to overwrite that too .
Let's see this example here.
#include <iostream>
using std::cout;
using std::endl;
class A {
public:
virtual void doNothing() = 0;
void erase() {
memset((void*)this, 0, sizeof(A));
}
private :
int a;
};
class B : public A {
public:
void doNothing() { }
};
int main() {
A * p = new B;
cout << sizeof(A) << " " << sizeof(int) << endl;
p->erase(); //Oops - You are erasing the VTBL here.
//How will I know my type from now on ?
cout << sizeof(A) << " " << sizeof(int) << endl;
p->doNothing(); //Segmentation fault ....
delete p;
}
And this is extremely non-intuitive and buggy.
That explains why you should never use this.
--
Karthik.