Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do the equivalent of memset(this, ...) without clobbering the vtbl?

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).

like image 510
Peeter Joot Avatar asked Oct 15 '12 19:10

Peeter Joot


1 Answers

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.

like image 115
AShelly Avatar answered Oct 21 '22 13:10

AShelly