"Type of bit field too small for number of bits" 错误是 C++ 标准的一部分吗?
Is the "Type of bit field too small for number of bits" error part of the C++ standard?
以下代码在 Visual Studio 2008 年生成 MSVS Compiler Error C2034:
struct TestStruct {
unsigned short var1 : 7;
unsigned short : 9;
bool var2 : 1;
bool : 15; // C2034
};
error C2034: 'TestStruct::<alignment member>': type of bit field too small for number of bits
然而,下面的代码编译成功,这看起来有点傻,因为我认为编译器可以自动完成:
struct TestStruct {
unsigned short var1 : 7;
unsigned short : 9;
bool var2 : 1;
bool : 7;
bool : 8;
};
然而,这两个代码片段都可以在我的 Linux GCC 编译器上编译。根据 C++ 标准,一个编译器是否比另一个更正确?如果是,是哪个,为什么?
是的,这是 MSVS 中的错误。该标准在 [class.bit]/1
中说明
[...]The value of the integral constant expression may be larger than the number of bits in the object representation (3.9) of the bit-field’s type; in such cases the extra bits are used as padding bits and do not participate in the value representation (3.9) of the bit-field.[...]
所以编译器应该添加额外的填充并且只让你有等于 CHAR_BIT * sizeof(bit_field_underlying_type)
.
的位数
以下代码在 Visual Studio 2008 年生成 MSVS Compiler Error C2034:
struct TestStruct {
unsigned short var1 : 7;
unsigned short : 9;
bool var2 : 1;
bool : 15; // C2034
};
error C2034: 'TestStruct::<alignment member>': type of bit field too small for number of bits
然而,下面的代码编译成功,这看起来有点傻,因为我认为编译器可以自动完成:
struct TestStruct {
unsigned short var1 : 7;
unsigned short : 9;
bool var2 : 1;
bool : 7;
bool : 8;
};
然而,这两个代码片段都可以在我的 Linux GCC 编译器上编译。根据 C++ 标准,一个编译器是否比另一个更正确?如果是,是哪个,为什么?
是的,这是 MSVS 中的错误。该标准在 [class.bit]/1
中说明[...]The value of the integral constant expression may be larger than the number of bits in the object representation (3.9) of the bit-field’s type; in such cases the extra bits are used as padding bits and do not participate in the value representation (3.9) of the bit-field.[...]
所以编译器应该添加额外的填充并且只让你有等于 CHAR_BIT * sizeof(bit_field_underlying_type)
.