I know that memset is frowned upon for class
initialization. For example, something like the following:
class X { public:
X() { memset( this,
Leverage the fact that a static instance is initialised to zero: https://ideone.com/GEFKG0
template
struct clearable
{
void clear()
{
static T _clear;
*((T*)this) = _clear;
};
};
class test : public clearable
{
public:
int a;
};
int main()
{
test _test;
_test.a=3;
_test.clear();
printf("%d", _test.a);
return 0;
}
However the above will cause the constructor (of the templatised class) to be called a second time.
For a solution that causes no ctor call this can be used instead: https://ideone.com/qTO6ka
template
struct clearable
{
void *cleared;
clearable():cleared(calloc(sizeof(T), 1)) {}
void clear()
{
*((T*)this) = *((T*)cleared);
};
};
...and if you're using C++11 onwards the following can be used: https://ideone.com/S1ae8G
template
struct clearable
{
void clear()
{
*((T*)this) = {};
};
};