Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the special regarding int :0 in C++

Tags:

c++

c++11

c++14

struct S {
    char a;         // location #1
    int b:5,        // location #2
    int c:11,
    int :0,         // note: :0 is "special"
    int d:8;        // location #3
    struct {int ee:8;} e;   // location #4
};

It seems that int :0 member variable of a struct does not occupy any memory space, and it is marked as: // note: :0 is "special"

Does anybody know what is the special usage of int :0 here? Thanks

PS: sample code is quoted from http://www.stroustrup.com/C++11FAQ.html#memory-model

like image 844
Xiong Zou Avatar asked Dec 08 '22 10:12

Xiong Zou


2 Answers

int:0; declares a zero-width bitfield.

This occupies no memory, but explicitly separates the bitfields declared prior to it from the bitfields declared afterwards into separate memory locations.

This may potentially introduce padding into your structure, but this can be important for concurrent accesses.

In your example, b and c occupy the same memory location, so you cannot have one thread access b while another accesses c. On the other hand, the zero-width bitfield ensures that d is a separate memory location, so b and d can be accessed concurrently from separate threads without synchronization.

Without the zero-width bitfield, on 32-bit or 64-bit platforms, it is likely that the compiler would make b,c and d part of the same machine word, so safe concurrent access would be impossible without special instructions whereas with the zero-width bitfield, the compiler would ensure that they are stored in separate machine words, or appropriate instructions are used to ensure that concurrent access is safe.

like image 103
Anthony Williams Avatar answered Dec 10 '22 00:12

Anthony Williams


From https://en.cppreference.com/w/cpp/language/bit_field

The value zero is only allowed for nameless bitfields and has special meaning: it specifies that the next bit field in the class definition will begin at an allocation unit's boundary.

like image 40
Stu Avatar answered Dec 10 '22 00:12

Stu