1

I understand that Bitsets can't be dynamically allocated because they are based on Template Parameters.But why were bitsets implemented that way?

Thanks

nikel
  • 3,402
  • 11
  • 45
  • 71

2 Answers2

2

This is done to make sure bitsets have characteristics as close as possible to those of an unsidned integer (which is widely used to represent bitsets otherwise). One of them, responsible for the size being a template parameter is a requirement to have no implicit dynamic memory allocation.

For situations when dynamic size is more important than other characteristics one can use boost dynamic_bitset.

bobah
  • 18,364
  • 2
  • 37
  • 70
1

Efficiency? Because it's a common use-case? If you want a dynamic bit sets consider vector<bool>. It even has some bit operations defined on it. But read this first.

Community
  • 1
  • 1
john
  • 85,011
  • 4
  • 57
  • 81
  • Could You elaborate on Why that is Efficient? – nikel Nov 03 '12 at 10:57
  • 2
    Because, for instance, if you write `bitset<32>` many implementations will be smart enough to know that just needs a single `int` to hold all the bits. The compiler will then hopefully be smart enough to compile the code to simple machine code instructions. You would never get that level of optimization with a dynamic bit set because neither the implementing code nor the compiler can make assumptions about what size the bit set really is. – john Nov 03 '12 at 10:59