问题
I have a struct which contains bit-fields:
struct Foo {
unsigned a : 16, b : 16;
};
And I want to know if I can use aggregate initialization on it's bit-fields. For example:
struct Foo bar = {13, 42};
I note that this does work in gcc 5.1 and Visual Studio 2015. I'd just like something to certify this was standard approved initialization for both C and C++.
回答1:
From C++14 [dcl.init.aggr]
we have
An aggregate is an array or a class (Clause 9) with no user-provided constructors (12.1), no private or protected non-static data members (Clause 11), no base classes (Clause 10), and no virtual functions (10.3).
So Foo
is an aggregate an qualifies for aggregate initialization. Then we have
When an aggregate is initialized by an initializer list, as specified in 8.5.4, the elements of the initializer list are taken as initializers for the members of the aggregate, in increasing subscript or member order.[...]
and
Static data members and anonymous bit-fields are not considered members of the class for purposes of aggregate initialization.
So in your case they will be initialized since they are not anonymous and they will be initialized in the order they appear in the struct
.
From C11 6.2.5(21) we have
Arithmetic types and pointer types are collectively called scalar types. Array and structure types are collectively called aggregate types.46)
So in C we are still dealing with an aggregate. Then in 6.7.9(9) we have
Except where explicitly stated otherwise, for the purposes of this subclause unnamed members of objects of structure and union type do not participate in initialization. Unnamed members of structure objects have indeterminate value even after initialization.
and 6.7.9(17)
Each brace-enclosed initializer list has an associated current object. When no designations are present, subobjects of the current object are initialized in order according to the type of the current object: array elements in increasing subscript order, structure members in declaration order, and the first named member of a union.148) In contrast, a designation causes the following initializer to begin initialization of the subobject described by the designator. Initialization then continues forward in order, beginning with the next subobject after that described by the designator.149)
So we have the same behavior as in C++ where anonymous bit fields are not initialized but since they are named they will be initialized in the order they appear in the struct
.
来源:https://stackoverflow.com/questions/34856936/is-aggregate-initialization-of-bit-fields-allowed