指向 std::vector<bool> 的元素时出现编译器错误? [英] compiler error when pointing to an element of std::vector<bool>?
问题描述
尝试使用 std::vector
我有一个编译器错误,这让我感到非常惊讶.
Trying to use std::vector<bool>
I have a compiler error that is very surprising to me.
简而言之,获取 std::vector
元素的地址并将其分配给 unsigned char
指针:
In short taking the address of an element of a std::vector<unsigned char>
and assigning it to a unsigned char
pointer:
std::vector<unsigned char> test(10);
unsigned char *pb = &test[0];
工作得很好,同时尝试用 std::vector
做同样的事情会导致编译器错误:
works perfectly well, while trying to do the same thing with a std::vector<bool>
results in a compiler error:
int main() {
std::vector<bool> test(10);
bool *pb = &test[0]; // line 4, compile error
return 0;
}
在 Visual Studio 上,它说的是:
On Visual Studio, it says something like:
std::vector bool cannot convert std::_Vb_reference<_Alloc> * to bool *
而键盘(参见 http://codepad.org/vaiN3iEq 上的示例)说:
while codepad (see example at http://codepad.org/vaiN3iEq) says:
cc1plus: warnings being treated as errors
In function 'int main()':
Line 4: warning: taking address of temporary
Line 4: error: cannot convert '__gnu_norm::_Bit_reference*' to 'bool*' in initialization
compilation terminated due to -Wfatal-errors.
我认为 bool
和 unsigned char
在内部是相同的(只是一个 1 字节类型,有一些编译器的东西来强制 bool
只允许真/假值).但没想到会出现这样的问题!知道为什么吗?!
I thought both bool
and unsigned char
were internally the same (just a 1 byte type, with some compiler stuffs to enforce bool
to allow only true/false values). But I was not expecting such problem! Any idea why?!
请注意,我知道 bitsets 并且对在此处使用它们不感兴趣.
Note that I know of bitsets and am not interested in using them here.
推荐答案
是的,bool
和 unsigned char
通常各自占用相同数量的内存,但是不会使 vector
和 vector
相同!
Yes, bool
and unsigned char
typically take the same amount of memory on their own, but that does not make vector<bool>
and vector<unsigned char>
the same!
vector
被标准给予了非常、非常 的特殊处理,以便尽可能接近地打包元素(1990 年代有人认为这很聪明,因为 bool
只有两种状态之一),结果就是你所看到的:它的元素是不可寻址的.
vector<bool>
is given very, very special treatment by the standard in order to pack elements as close as possible (which someone in the 1990s thought would be clever, since a bool
has one of only two states), and the result is what you've seen: its elements are non-addressable.
避免!
这篇关于指向 std::vector<bool> 的元素时出现编译器错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!