Home > Software engineering >  If std::vector<bool> was rewritten to use the standard vector implementation, how would that b
If std::vector<bool> was rewritten to use the standard vector implementation, how would that b

Time:11-04

According to the answers in this question, std::vector<bool> implements "special" logic (to allow each boolean value to be stored in a single bit, rather than taking up an entire byte), and because of that, it doesn't quite fulfil the requirements of an STL container and its use is therefore discouraged. However, the "special" logic is retained for backward-compatibility reasons.

My question is, if the C implementers were to throw out the "special" logic and turn std::vector<bool> into just another specialization of the std::vector template, what backwards compatibility problems would that cause? i.e. is there some special behavior that old software might be relying on that requires the bit-packing implementation to be retained? (the only thing I can think of is that some old software in a RAM-constrained environment might be relying on the eightfold-reduction in memory usage in order to function, but that seems like a relatively minor concern in most contexts)

CodePudding user response:

Firstly, that would be an ABI break. A major reason why changing anything from the standard library is difficult.

Secondly, anything using flip would break:

#include <vector>

int main() {
  std::vector<bool> vec { true };
  vec[0].flip(); // can't be done with regular bool
}

Thirdly, there would probably be other problems due to overload resolution someone probably relies on.


Side note: You can always use boost::container::vector instead, which is not specialized for bool.

CodePudding user response:

I believe the crux of the problem is DLL compatibility.

If they change the memory of any standard classes, then that class can't be passed across a DLL boundary, because we don't know which memory format the DLL was expecting, unless we know for certain that they were compiled with the same C version.

This is also why Windows APIs take pointers to structs, and the first member of the struct is the size. This allows them to append members to the struct in new versions of Windows, but older applications will continue to be able to call the methods.

  • Related