为什么位字段不允许作为 class 的静态数据成员
Why are bit fields not allowed as static data members of a class
任何人都可以解释不允许位字段作为 class 的静态成员背后的原因吗?例如,class 定义如下:
class A{
public:
A() {}
~A(){}
private:
static int mem :10;
};
int A::mem;
无法编译。
用不同的编译器编译此 class:-
1- g++ 抛出错误:-
错误:静态成员'mem'不能是位域
static int mem :10;
错误:‘int A::mem’不是‘class A’的静态数据成员
整数A::mem;
2- clang 抛出错误:-
错误:静态成员'mem'不能是位域
static int mem :10;
3-Visual Studio 15 抛出错误:-
'A::mem'::非法存储class
'int A::mem':不允许成员函数重新声明
主要原因是因为 C++ 标准明确指出:
A bit-field shall not be a static member. A bit-field shall have integral or enumeration type ([basic.fundamental]). A bool value can successfully be stored in a bit-field of any nonzero size. The address-of operator & shall not be applied to a bit-field, so there are no pointers to bit-fields. A non-const reference shall not be bound to a bit-field ([dcl.init.ref]). [ Note: If the initializer for a reference of type const T& is an lvalue that refers to a bit-field, the reference is bound to a temporary initialized to hold the value of the bit-field; the reference is not bound to the bit-field directly. See [dcl.init.ref]. — end note ]
理由是什么?好吧,位域是 C 的遗留物。它们只允许作为结构或联合域开始。就个人而言,我想不出静态位域成员可以发挥作用的上下文。
此外,实际上关于位域的所有内容都已经实现定义,让静态数据以完全实现定义的方式运行,恕我直言,这是一个非常糟糕的主意。
标准禁止它的原因是静态数据成员需要在某处实例化 - 在您的示例中,某处的编译单元需要包含:
int A::mem :10;
这是无效的,与独立的非成员位域变量相同,例如:
int foo :10;
无效。
当然有人会问为什么禁止这样做,但这是一个更广泛的问题,与成为 class 成员无关。
任何人都可以解释不允许位字段作为 class 的静态成员背后的原因吗?例如,class 定义如下:
class A{
public:
A() {}
~A(){}
private:
static int mem :10;
};
int A::mem;
无法编译。
用不同的编译器编译此 class:-
1- g++ 抛出错误:-
错误:静态成员'mem'不能是位域
static int mem :10;
错误:‘int A::mem’不是‘class A’的静态数据成员
整数A::mem;
2- clang 抛出错误:-
错误:静态成员'mem'不能是位域
static int mem :10;
3-Visual Studio 15 抛出错误:-
'A::mem'::非法存储class
'int A::mem':不允许成员函数重新声明
主要原因是因为 C++ 标准明确指出:
A bit-field shall not be a static member. A bit-field shall have integral or enumeration type ([basic.fundamental]). A bool value can successfully be stored in a bit-field of any nonzero size. The address-of operator & shall not be applied to a bit-field, so there are no pointers to bit-fields. A non-const reference shall not be bound to a bit-field ([dcl.init.ref]). [ Note: If the initializer for a reference of type const T& is an lvalue that refers to a bit-field, the reference is bound to a temporary initialized to hold the value of the bit-field; the reference is not bound to the bit-field directly. See [dcl.init.ref]. — end note ]
理由是什么?好吧,位域是 C 的遗留物。它们只允许作为结构或联合域开始。就个人而言,我想不出静态位域成员可以发挥作用的上下文。
此外,实际上关于位域的所有内容都已经实现定义,让静态数据以完全实现定义的方式运行,恕我直言,这是一个非常糟糕的主意。
标准禁止它的原因是静态数据成员需要在某处实例化 - 在您的示例中,某处的编译单元需要包含:
int A::mem :10;
这是无效的,与独立的非成员位域变量相同,例如:
int foo :10;
无效。
当然有人会问为什么禁止这样做,但这是一个更广泛的问题,与成为 class 成员无关。