Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are bit fields not allowed as static data members of a class

Tags:

c++

bit-fields

Can anyone explain the reason behind not allowing bit fields as static member of a class? For example, a class defined like:

class A{
public:
    A() {}
    ~A(){}
private:
    static int mem :10;
};
int A::mem;

doesn't compile.

Compiling this class with different compilers:-

1- g++ throws error:-

error: static member 'mem' cannot be a bit-field

static int mem :10;

error: ‘int A::mem’ is not a static data member of ‘class A’

int A::mem;

2- clang throws error:-

error: static member 'mem' cannot be a bit-field

static int mem :10;

3-Visual Studio 15 throws error:-

'A::mem'::illegal storage class

'int A::mem':member function redeclaration not allowed

like image 565
Dinesh Maurya Avatar asked Mar 29 '17 05:03

Dinesh Maurya


2 Answers

The main reason is because that's what the C++ standard says explicitly:

[class.bit] 12.2.4/3

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 ]

The reasoning for it? Well, bit-fields are a carry-over from C. They are allowed only as struct or union fields there to begin with. Personally, I can't think of a context where a static bit-field member can be useful.

Furthermore, practically everything about bit-fields is implementation defined already, and letting static data behave in a completely implementation defined manner, is IMHO a very bad idea.

like image 153
StoryTeller - Unslander Monica Avatar answered Nov 11 '22 19:11

StoryTeller - Unslander Monica


The reason the standard prohibits it is because static data members need to be instantiated somewhere - in your example, a compilation unit somewhere would need to contain:

int A::mem :10;

which is invalid, in the same way that a standalone non-member bitfield variable such as:

int foo :10;

is invalid.

Of course one can ask why this is prohibited, but that's a wider question not related to it being a class member.

like image 43
Jeremy Avatar answered Nov 11 '22 19:11

Jeremy