Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...