如何做等效的memset(这,...)没有clobbering vtbl? [英] How to do the equivalent of memset(this, ...) without clobbering the vtbl?
问题描述
我知道memset被 class
初始化所困扰。例如,如下所示:
class X {public:
X(){memset ,sizeof(* this)); }
...
};
将会破坏 vtbl
code> virtual 函数。
我正在编写一个(浩瀚的)遗留代码库,是C-ish,但是用C ++编译,所以所有成员通常是POD,不需要传统的C ++构造函数。 C ++的使用逐渐演变(像虚拟函数),并且这使得没有意识到memset有这些额外的C ++牙齿的开发人员。
我想知道如果有是一个C ++安全的方法来做一个初始捕获全零初始化,可以跟随特定的成员初始化,其中零初始化是不适当的?
我发现类似的问题用于C ++初始化的memset 和使用memset 调零派生结构。这两个都有不使用memset()的答案,但没有好的替代(特别是对于大型结构可能包含许多成员)。
对于每个发现 memset
调用的类,添加一个 memset
实际上,它不应忽略所有数据成员的指针和大小参数。
<指针,它应该与
this
比较。在匹配时,对对象执行正确的操作,在不匹配时,重新路由到全局函数。 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.
这篇关于如何做等效的memset(这,...)没有clobbering vtbl?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!