What is the size of bitset in C++

风流意气都作罢 提交于 2019-12-17 18:38:39

问题


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++?


回答1:


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




回答2:


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++.




回答3:


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.




回答4:


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.




回答5:


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.)



来源:https://stackoverflow.com/questions/12459563/what-is-the-size-of-bitset-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!