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)
Yes, it means that the implementation of std::vector<bool> is largely up to the compiler. It might not be optimized at all, or it might be optimized in an implementation-specific way. Generally, you find this out by consulting the documentation for your compiler.
A bool vector has the methods of a vector <T> if instead of the placeholder T is used for the type bool. The vector <bool> specialization also offers the Void flip () method, which negates all elements.
std::vector<bool> behaves similarly to std::vector, but in order to be space efficient, it: Does not necessarily store its elements as a contiguous array.
The standardised specialisation of std::vector<bool> is widely considered to be an error in hindsight by the community. If you are looking for a standardised set of bits then I think it would be wise to consider std::bitset
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With