If 1 bool is 1byte [8 bits] t开发者_高级运维hen would a packed structure of 4 bools be 32bits or 4? The pack directive removes the alignment requirement, but would it make sets of bools more efficient [memory wise]?
Yes. Even a packed structure of booleans will use at least 8 bits per boolean. Unless you use bit fields.
4 bool
s.
Each bool
needs a unique address (as you can take a bool
's address). If you use a bitfield, you can reduce the size to 1 bool, but you won't be able to get the address of an individual bitfield.
The size of a bool could possibly vary from OS to OS and language to language. I've seen it being a byte, a word and an int (which in turn could be anything as well). But if sizeof(bool) is 1, then a packed structure of bools will be 4 (bytes) (thus 32 bits)
Rather than messing with packing and alignment, why not use:
std::vector<bool>
From : http://www.cplusplus.com/reference/stl/vector/
It is optimized (or should be) internally to be a bitfield. Try it, you'll see the memory it uses is consistent with a single bit per value.
Otherwise you can always roll your own library or use the limited FD_SET macros.
That is an implementation-defined. The standard doesn't define the size of a boolean.
EDIT
This is from the standard :
5.3.3 Sizeof
The sizeof operator yields the number of bytes in the object representation of its operand. The operand is either an expression, which is not evaluated, or a parenthesized type-id. The sizeof operator shall not be applied to an expression that has function or incomplete type, or to an enumeration type before all its enumerators have been declared, or to the parenthesized name of such types, or to an lvalue that designates a bit-field. sizeof(char), sizeof(signed char) and sizeof(unsigned char) are 1; the result of sizeof applied to any other fundamental type (3.9.1) is implementation-defined. [Note: in par- ticular, sizeof(bool) and sizeof(wchar_t) are implementation-defined.69) ] [Note: See 1.7 for the definition of byte and 3.9 for the definition of object representation. ]
精彩评论