- Mastering the C++17 STL
- Arthur O'Dwyer
- 214字
- 2021-07-08 10:20:26
Pitfalls with vector<bool>
The std::vector template has one special case: std::vector<bool>. Since the bool datatype has only two possible values, the values of eight bools can be packed into a single byte. std::vector<bool> uses this optimization, which means that it uses eight times less heap-allocated memory than you might naturally expect.

The downside of this packing is that the return type of vector<bool>::operator[] cannot be bool&, because the vector doesn't store actual bool objects anywhere. Therefore, operator[] returns a customized class type, std::vector<bool>::reference, which is convertible to bool but which is not, itself, a bool (types like this are often called "proxy types" or "proxy references").
The result type of operator[] const is "officially" bool, but in practice, some libraries (notably libc++) return a proxy type for operator[] const. This means that code using vector<bool> is not only subtle but sometimes non-portable as well; I advise avoiding vector<bool> if you can:
std::vector<bool> vb = {true, false, true, false};
// vector<bool>::reference has one public member function:
vb[3].flip();
assert(vb[3] == true);
// The following line won't compile!
// bool& oops = vb[0];
auto ref = vb[0];
assert((!std::is_same_v<decltype(ref), bool>));
assert(sizeof vb[0] > sizeof (bool));
if (sizeof std::as_const(vb)[0] == sizeof (bool)) {
puts("Your library vendor is libstdc++ or Visual Studio");
} else {
puts("Your library vendor is libc++");
}
- Learning NServiceBus(Second Edition)
- ASP.NET Core 5.0開發入門與實戰
- Julia機器學習核心編程:人人可用的高性能科學計算
- Django Design Patterns and Best Practices
- 自然語言處理Python進階
- Node.js Design Patterns
- Android程序設計基礎
- 好好學Java:從零基礎到項目實戰
- HTML5秘籍(第2版)
- 輕松上手2D游戲開發:Unity入門
- SciPy Recipes
- Java圖像處理:基于OpenCV與JVM
- Java Web應用開發項目教程
- 實戰Java高并發程序設計(第2版)
- 并行編程方法與優化實踐