Why are non-const references to bitfields prohibited?

前端 未结 2 599
梦如初夏
梦如初夏 2021-01-02 04:09

Section 9.6/3 in C++11 is unusually clear: \"A non-const reference shall not be bound to a bit-field.\" What is the motivation behind this prohibition?

I understand

2条回答
  •  醉梦人生
    2021-01-02 04:53

    You can’t take a non-const reference to a bitfield for the same reason you can’t take its address with &: its actual address is not necessarily aligned to char, which is definitionally the smallest addressable unit of memory in the C++ abstract machine. You can take a const reference to it because the compiler is free to copy the value, as it won’t be mutated.

    Consider the issue of separate compilation. A function taking a const uint32_t& needs to use the same code to operate on any const uint32_t&. If different write behaviour is required for ordinary values and bitfield values, then the type doesn’t encode enough information for the function to work correctly on both.

提交回复
热议问题