1

Possible Duplicate:
One-byte bool. Why?

I want to add a boolean variable to a class. However, this class is pretty size-sensitive, and as a result I'm loath to add another field. However, it is composed of a pile of members that are at least a char wide, and a single other bool.

If I were hand-writing this code, I would implement those boolean fields as bits in the last byte or so of the object. Since accesses have to be byte-aligned, this would cause no spacial overhead.

Now, do compilers typically do this trick? The only reason I can of for them not to is because it would involve an additional mask to get that bit out of there.

Community
  • 1
  • 1
alexgolec
  • 26,898
  • 33
  • 107
  • 159

3 Answers3

3

No, compilers can't do this trick because the address of each member has to be distinct. If you want to pack a fixed number of bits, use std::bitset. If you need a variable number of bits use boost::dynamic_bitset.

Mark B
  • 95,107
  • 10
  • 109
  • 188
2

No, I don't know of any compilers which optimize a bool down to a bit.

You can force this behavior via:

unsigned int m_firstBit : 1;
unsigned int m_secondBit : 1;
unsigned int m_thirdBit : 1;

As for reasons why not, it would likely violate some language guarantees. For instance, you couldn't pass &myBool to a function which takes a bool* if it doesn't have its own reserved byte.

StilesCrisis
  • 15,972
  • 4
  • 39
  • 62
0

Compilers typically do not do that, but you could use std::bitset<2> to pack two bools into one byte.

StilesCrisis
  • 15,972
  • 4
  • 39
  • 62
David
  • 51
  • 4