9

The question is really simple (to ask), std::bitset<32> is the same thing as uint32_t for the memory? Or it's more like std::array<bool, 32> ?

I usually do something like:

uint32_t  index : 20;
uint32_t  magic : 12;

So it's the same as this code ?

std::bitset<20>  index;
std::bitset<12>  magic;
Mathieu Van Nevel
  • 1,428
  • 1
  • 10
  • 26

2 Answers2

7
uint32_t  index : 20;
uint32_t  magic : 12;

So it's the same as this code ?

std::bitset<20>  index;
std::bitset<12>  magic;

Absolutely not, and it's very important that you understand the difference.

First, the internal representation of std::bitset<> is down the implementation.

With that out of the way we should examine the difference between the two code snippets above.

In c++ a bitfield is not a discrete object. This has important implications in multi-threaded code.

This is because c++11 and greater guarantees that unprotected access from two threads to two discrete objects is safe, but access of the same non-const object by two more more threads is a data race unless protected by a mutex.

In the above bitset code it would be correct to say:

thread1: index = 10;

thread2: auto x = magic;

Because they are discrete objects and therefore guaranteed not to cause data races when accessed from different threads.

In the bitfield code this would not be safe. The update of index would be a race with the reading of magic, and this is undefined behaviour.

Richard Hodges
  • 68,278
  • 7
  • 90
  • 142
  • You're right I forget the multi-threaded implication. I know that bitfield share memory. Then if I'm going to do some multi-threaded code, I should look how the code is going to work before choose between bitset or bitfield. – Mathieu Van Nevel Dec 06 '16 at 16:22
  • @MathieuVanNevel The best advice I can offer is to avoid bitfields altogether unless you are writing to memory-mapped I/O. – Richard Hodges Dec 06 '16 at 16:31
  • well I'm going to try to remove bitfield for bitset anyway. I understand why alexeykuzmin0 said yes, but you're right that's not the right answer for this question. Don't know why Stargateur was so downvote. – Mathieu Van Nevel Dec 06 '16 at 16:53
2

A bit field need a struct

struct {
    uint32_t index : 20;
    uint32_t magic : 12;
}

so it's not the same that

std::bitset<20>  index;
std::bitset<12>  magic;

"Multiple adjacent bit fields are usually packed together (although this behavior is implementation-defined): ".

you have two std::bitset so they can't share same memory, so it's not the same thing.

Stargateur
  • 24,473
  • 8
  • 65
  • 91