[CppAD] vector<bool>

Robert P. Goddard Robert_Goddard at apl.washington.edu
Mon Oct 17 14:35:25 EDT 2005


Coin-or,

Brad Bell asked me to pass on my thoughts regarding the drawbacks of 
specializing a template vector class for the bool case. The core of my 
comment is a reference: Read Scott Meyers's book,  "Effective STL: 50 
Specific Ways to Improve Your Use of the Standard Template Library" 
(Addison-Wesley 2001). In particular, his Item 18 is: "Avoid using 
vector<bool>" followed by 3 pages of reasons, starting with:

"As an STL container, there are really only two things wrong with 
vector<bool>. First, it's not an STL container. Second, it doesn't hold 
bools. Other than that, there's not much to object to."

The return type of vector<T>::operator[] is supposed to be T&. The bool 
specialization returns a proxy object instead. "bool *pb = &v[0];" is 
supposed to compile, but it doesn't. You are supposed to be able to use 
such a pointer to pass a vector's contents to a C API. You can do this 
for every C-compatible type except bool (even though C99 does now 
support bool). In addition, access to the specialized vector<bool> is 
slower than it has to be because of the shift-and-mask operations that 
must happen under the covers.

The correct way, which the Standard missed, is to leave vector<bool> 
un-specialized, so that it really is an STL container, and then provide 
an additional almost-container class for those users who really do need 
to pack bools into bits. Alas, we don't have that choice: Specializing 
vector<bool> deprived us of the option of actually having an STL vector 
containing bools. Bad mistake.

Robert P. Goddard




More information about the CppAD mailing list