I know that memset is frowned upon for class
initialization. For example, something like the following:
class X { public:
X() { memset( this, 0, sizeof(*this) ) ; }
...
} ;
will clobber the vtbl
if there's a virtual
function in the mix.
I'm working on a (humongous) legacy codebase that is C-ish but compiled in C++, so all the members in question are typically POD and require no traditional C++ constructors. C++ usage gradually creeps in (like virtual functions), and this bites the developers that don't realize that memset has these additional C++ teeth.
I'm wondering if there is a C++ safe way to do an initial catch-all zero initialization, that could be followed by specific by-member initialization where zero initialization isn't appropriate?
I find the similar questions memset for initialization in C++, and zeroing derived struct using memset. Both of these have "don't use memset()" answers, but no good alternatives (esp. for large structures potentially containing many many members).
For each class where you find a memset
call, add a memset
member function which ignores the pointer and size arguments and does assignments to all the data members.
edit:
Actually, it shouldn't ignore the pointer, it should compare it to this
. On a match, do the right thing for the object, on a mismatch, reroute to the global function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With