What is the size of the bit set in C ++

I want to know how the 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 a conclusion like 4. What is the explanation for this?

Also is there a method for allocating space in bits in C ++?

+4
source share
5 answers

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

  • If the internal representation is 32bit (for example, unsigned in 32-bit systems) as 4 * ((N + 31) / 32)
  • If the internal representation is 64 bits (for example, unsigned length in 64-bit systems) as 8 * ((N + 63) / 64)

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

+5
source

I get a conclusion like 4. What is the explanation for this?

There is no information in the standard about how bitset should be implemented. This implementation is defined, see the bitset header your compiler.

Also there is a method for allocating space in bits in C ++?

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

+6
source

Your processor does not work with individual bits, but with bytes and words. In your case, sizeof (bits) results in 4, because the compiler decided to align this data structure with 4 bytes.

+5
source

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

+1
source

You cannot address individual bits, the lowest address block is a byte. So no, you cannot pinpoint bits accurately.

Filling is another thing - you almost always get more allocated bytes that you requested, this is for optimization purposes. Byte addressing at non-32b borders is often expensive, addressing bytes on an x64 processor that are not at 64b borders results in an exception. (speaking of the Intel platform.)

0
source

Source: https://habr.com/ru/post/1434602/


All Articles