Commit c3a10de4 authored by scott snyder's avatar scott snyder
Browse files

Add recommendation to avoid bit fields.

parent 7287a102
......@@ -1932,6 +1932,54 @@ for (int i=0; i < lots; i++) {
in low-level code to avoid pointer aliasing (see [[no-reinterpret-cast]]).
- *Avoid using bit fields.* [<<avoid-bitfields>>]
Bit fields are a feature that C++ inherited from C that allow one
to specify that a member variable should occupy only a specified
number of bits, and that it can be packed together with other such members.
class C
unsigned int a : 2; // Allocated two bits
unsigned int b : 3; // Allocated three bits
It may be tempting to use bit fields to save space in data written
to disk, or packing and unpacking raw data. However, this usage is
not portable. The C++ standard has this to say:
Allocation of bit-fields within a class object is
implementation-defined. Alignment of bit-fields is
implementation-defined. Bit-fields are packed into some addressable
allocation unit. [ Note: Bit-fields straddle allocation units on some
machines and not on others. Bit-fields are assigned right-to-left on
some machines, left-to-right on others. -- end note ]
Besides portability issues, there are other other potential issues
with bit fields that could be confusing: bit fields look like class members
but obey subtly different rules. For example, one cannot form a reference
to a bit field or take its address. There is also an issue of data
races when writing multithreaded code. It is safe to access two
ordinary class members simultaneously from different threads,
but not two adjacent bit fields. (Though it is safe to access
simultaneously two bit field members separated by an ordinary member.
This leads to be possibility that thread-safety of bit field access
could be compromised by the removal of an unrelated member.)
Access to bit fields also incurs a CPU penalty.
In light of this, it is best to avoid bit fields in most cases.
Exceptions would be cases where saving memory is very important
and the internal structure of the class is not exposed.
For some cases, =std::bitset= can be a useful, portable replacement
for bit fields.
- *Do not use asm (the assembler macro facility of C++).* [<<no-asm>>]
For those rare use cases where an =asm= might be needed, the use
......@@ -2522,6 +2570,11 @@ The comment includes the fact that it is the perpendicular distance.
* Changes
** Version 0.3
- Add recommendation to avoid bit fields.
** Version 0.2
- Small typo fixes.
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment