17
votes

I want to know how bitset actually allocates memory. I read from some blog that it takes up memory in bits. However when i run the following code:

   bitset<3> bits = 001;
   cout<<sizeof(bits);

I get the output as 4. What is the explanation behind it?

Also is there a method to allocate space in bits in C++?

5
You cannot allocate space in bits, since that’s not how the C++ abstract machine works. Just like you cannot buy half of a banana in a supermarket, you cannot allocate half bytes. - user1203803
It will round up to the least amount of bytes it takes to store N bits, at least. The compiler will add alignment and stuff to make accessing the data faster, but how it does that exactly is implementation-defined. - user1203803
"Also is there a method to allocate space in bits in C++?", yes, but you can only allocate 8 of them at a time... - Luchian Grigore
@LuchianGrigore not always 8; it depends on CHAR_BIT. - user1203803
@LuchianGrigore s/pedantry/correctness/ - user1203803

5 Answers

13
votes

You can approximate sizeof(bitset<N>) as:

  1. If internal representation is 32bit (like unsigned on 32bit systems) as 4 * ((N + 31) / 32)
  2. If internal representation is 64bit (like unsigned long on 64bit systems) as 8 * ((N + 63) / 64)

It seems that the first is true: 4 * ((3 + 31) / 32) is 4

8
votes

I get the output as 4. What is the explanation behind it?

There is no information in standard about how bitset should be realized. It's implementation defined, look at bitset header of your compiler.

Also is there a method to allocate space in bits in C++?

No, there is no method to allocate space in bits in C++.

8
votes

Your CPU doesn't operate with individual bits, but with bytes and words. In your case, sizeof(bits) results in 4 because compiler decided to align this datastructure to 4 bytes.

1
votes

Typically on a 32-bit processor, the compiler will make the allocated memory size a multiple of 4 bytes, and so the nearest multiple of 4 greater than 3/8 is 4 bytes.

0
votes

You cannot address separate bits, the lowest adressable unit is byte. So no, you cannot allocate bits precisely.

Another thing is padding - you almost always get more bytes allocated that you asked for, this is for optimalization purposes. Addressing bytes not on 32b boundaries is often expensive, addressing bytes on x64 CPU that are not on 64b boundaries results in exception. (speaking of Intel platform.)