Reference const to bitfield value

Viewed 72

Is it safe to create a reference const to a bitfield value? Have a look in the following example

typedef struct
{
    int a:1;
}x_t;

int main() {
   x_t x;
   bool const &  x2 = x.a; 
}
2 Answers

Is it safe to create a reference const to a bitfield value?

Yes, it's like the same as if you would write for example:

bool const& x3 = 42;

In your code the value of x.a is taken and a temporary object of type bool is created with the value of x.a assigned to it and then the reference is bound to that temporary object. So it's like creating a "view" (it's const) of the current value of x.a as a bool type. In oversimplification let's say it works as-if like:

const bool _some_hidden_temporary = x.a;
bool const& x2 = _some_hidden_temporary;

What you'll get is a const& to a temporary. if you toggle the bit in x_t it will not be reflected via the const& (x2).

The lifetime of the temporary is the lifetime of x2 (the end of main).

You can't have references to individual bits (in a bitfield) without implementing some kind of proxy class.

Related