Reputation: 353
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++?
Upvotes: 18
Views: 23424
Reputation: 55887
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 the <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++.
Upvotes: 10
Reputation: 24402
You can approximate sizeof(bitset<N>)
as:
4 * ((N + 31) / 32)
8 * ((N + 63) / 64)
It seems that the first is true: 4 * ((3 + 31) / 32)
is 4
Upvotes: 16
Reputation: 8526
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.
Upvotes: 1
Reputation: 953
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.
Upvotes: 8
Reputation: 16168
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.)
Upvotes: 0