Ben*_*tin 5 c++ constructor struct initialization bit-fields
在C++中,我有一个包含匿名位域结构的类.我想将其初始化为零,而无需手动写出所有字段.
我可以想象将初始化放在三个地方:
这个位域有很多字段,我宁愿不列出所有字段.
例如,请参阅以下代码:
class Big {
public:
Big();
// Bitfield struct
struct bflag_struct {
unsigned int field1 : 1;
unsigned int field2 : 2;
unsigned int field3 : 1;
// ...
unsigned int field20 : 1;
// bflag_struct(); <--- Here?
} bflag;
unsigned int integer_member;
Big *pointer_member;
}
Big::Big()
: bflag(), // <--- Can I zero bflag here?
integer_member(0),
pointer_member(NULL)
{
// Or here?
}
Run Code Online (Sandbox Code Playgroud)
其中一个更好吗?或者还有其他我想念的东西?
编辑:根据下面接受的答案(Ferruccio),我决定采用这个解决方案:
class Big {
// ...
struct bflag_struct {
unsigned int field 1 : 1;
// ...
bflag_struct() { memset(this, 0, sizeof *this); };
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
您可以使用union,虽然这会在访问字段时添加额外的间接级别:
class Big {
union {
struct {
unsigned int field1 : 1;
...
} fields;
unsigned int all_fields;
};
...
};
Big::Big()
: all_fields(0),
...
{
...
}
Run Code Online (Sandbox Code Playgroud)
MSVC允许联合内部的匿名结构(参见例如D3DMATRIXin 的定义<d3d9.h>),但这是一个非标准的C++扩展,如果可以,你应该避免使用它.