vector<bool>的确比较无脑,算是STL中的一个败笔吧。Scott Meyers是个好同志,指出了它的问题并给出了walkaround方法,具体细节同学们去看书吧。我倒是有一个问题:如果让vector<bool>成为一个好容器好公民,会怎样?现在的实现虽然不正统也不完美,但是如果有谁用了它,也不至于上吐下泻吧,可能这个就是实现者的一个出发点 - 不是为了美,而是为了实用。如果是这样,跟C++的设计初衷就吻合了。
要验证书中所说的问题很简单,几行代码就够了。
// main.cpp
#include <iostream>
#include <vector>
int main() {
std::vector<bool> answers;
answers.push_back(true);
answers.push_back(true);
answers.push_back(false);
// This line won't compile. It will cause error like "error: no viable conversion from '__bit_iterator<std::__1::vector<bool, std::__1::allocator<bool> >, false>' to 'bool *'"
//bool * b = &answers[0];
//std::cout << "the answer is " << *b << std::endl;
// But if you don't care too much about it's container or not,
// you can still use an iterator libe below.
auto it = &answers[0];
std::cout << "the answer is " << *it << std::endl;
for (auto && p : answers)
{
std::cout << "the answer is " << p << std::endl;
}
return 0;
}
如果你用的是clang,编译的脚本参考下面
#! /bin/sh
set -e
clang -std=c++17 -lstdc++ main.cpp -o ./item18
./item18