使用memset调零派生结构 [英] zeroing derived struct using memset
问题描述
我想清除派生结构的所有成员。
I want to zero out all members of a derived structure.
有几百个成员和更多的被添加每次一次,所以我觉得初始化它们显式地是容易出错的。
There are hundreds of members and more are added every once in a while so I feel that initializing them explicitly is error-prone.
结构没有虚函数,所有的成员字段都是内置的。
The structures have no virtual functions and all the member fields are built-in. However, they are not POD by virtue of having non-trivial constructors.
除了标准的皱眉外,你看到以下的问题吗?
Apart from the standard frowning on the practice, do you see any issues with the following?
struct Base
{
// Stuff
};
struct Derived : public Base
{
// Hundreds of fields of different built-in types
// including arrays
Derived()
{
::memset(reinterpret_cast<char*>this + sizeof (Base), 0, sizeof *this - sizeof (Base));
}
};
谢谢。
推荐答案
这假设 Base
基类子对象位于 Derived
的开头。如果你添加另一个基类,这将不会工作。
This assumes that the Base
base class subobject is located at the beginning of Derived
. This won't work if you add another base class.
此外,你的代码是错误的:指针运算是根据对象,而不是字节。您需要使用 reinterpret_cast< char *>(this)
按字节执行算术。
Further, your code is wrong: pointer arithmetic is performed in terms of objects, not in terms of bytes. You need to use reinterpret_cast<char*>(this)
to perform the arithmetic in terms of bytes. In any case, you still shouldn't do this.
使用价值初始化考虑以下非丑陋,符合标准的方法:
Consider the following, non-ugly, standards-conforming approach utilizing value initialization:
struct Derived : public Base
{
struct DerivedMembers { /* ... */ }
DerivedMembers data;
Derived() : data() { }
};
只要 DerivedMembers
没有构造函数,这将会初始化 data
的每个数据成员,这看起来像是你想要的行为。
As long as DerivedMembers
has no constructor, this will value initialize each of the data members of data
, which look like it's exactly the behavior you want.
或者,如果您希望在不使用数据
成员变量的情况下访问成员,请考虑使用另一个基类:
Or, if you want the members to be accessible without using a "data
" member variable, consider using another base class:
struct DerivedMembers { /* ... */ }
struct Derived : Base, DerivedMembers
{
Derived() : DerivedMembers() { }
};
这篇关于使用memset调零派生结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!