为什么是vector< bool>不是STL容器? [英] Why is vector<bool> not a STL container?
问题描述
Scott Meyers的Item 18表示避免向量< bool>
,因为它不是一个STL容器,它并不真正持有bools。
以下代码:
vector< bool> v;
bool * pb =& v [0];
无法编译,违反STL容器的要求。
错误:
无法转换std :: vector< bool> :: reference * {aka std :: _ Bit_reference *}'到初始化中的'bool *'
向量< T& :operator []
返回类型应该是T&,但为什么它是向量< bool>
b
$ b
向量< bool>
是什么?
进一步说:
deque< bool> v; //是一个STL容器,它真的包含bools
这可以用来替代<$
任何人都可以解释一下吗?
在这种情况下,由于您不能获取一个字节内的位,例如 operator []
不能返回 bool&
,而是返回一个代理对象其允许操纵所讨论的特定位。由于此代理对象不是 bool&
,因此您不能将其地址分配给 bool *
这种操作符调用在正常容器上的结果。这意味着 bool * pb =& v [0];
是无效的代码。
另一方面, deque
没有任何这样的特殊化调用所以每个bool需要一个字节,你可以取地址的值从
最后注意,MS标准库实现(可以说是)次优的,因为它使用小块大小的deques,这意味着使用deque作为替代并不总是正确的答案。
Scott Meyers's Item 18 says to avoid vector <bool>
as it's not an STL container and it doesn't really hold bools.
The following code:
vector <bool> v;
bool *pb =&v[0];
will not compile, violating requirement of STL containers.
Error:
cannot convert 'std::vector<bool>::reference* {aka std::_Bit_reference*}' to 'bool*' in initialization
vector<T>::operator []
return type is supposed to be T&, but why it's a special case for vector<bool>
?
What does vector<bool>
really consist of?
The Item further says:
deque<bool> v; // is a STL container and it really contains bools
Can this be used as an alternative to vector<bool>
?
Can anyone please explain this?
For space-optimization reasons, the C++ standard (as far back as C++98) explicitly calls out vector<bool>
as a special standard container where each bool uses only one bit of space rather than one byte as a normal bool would (implementing a kind of "dynamic bitset"). In exchange for this optimization it doesn't offer all the capabilities and interface of a normal standard container.
In this case, since you can't take the address of a bit within a byte, things such as operator[]
can't return a bool&
but instead return a proxy object that allows to manipulate the particular bit in question. Since this proxy object is not a bool&
, you can't assign its address to a bool*
like you could with the result of such an operator call on a "normal" container. In turn this means that bool *pb =&v[0];
isn't valid code.
On the other hand deque
doesn't have any such specialization called out so each bool takes a byte and you can take the address of the value return from operator[]
.
Finally note that the MS standard library implementation is (arguably) suboptimal in that it uses a small chunk size for deques, which means that using deque as a substitute isn't always the right answer.
这篇关于为什么是vector< bool>不是STL容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!