试图使用std::vector<bool>
我有一个编译器错误,这对我来说非常令人惊讶.
简而言之,取一个元素的地址std::vector<unsigned char>
并将其赋值给unsigned char
指针:
std::vector<unsigned char> test(10);
unsigned char *pb = &test[0];
Run Code Online (Sandbox Code Playgroud)
效果非常好,同时尝试std::vector<bool>
使用编译器错误导致同样的事情:
int main() {
std::vector<bool> test(10);
bool *pb = &test[0]; // line 4, compile error
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在Visual Studio上,它表示如下:
std::vector bool cannot convert std::_Vb_reference<_Alloc> * to bool *
Run Code Online (Sandbox Code Playgroud)
而codepad(参见http://codepad.org/vaiN3iEq上的例子)说:
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.
Run Code Online (Sandbox Code Playgroud)
我想这两个bool
和unsigned char
是内部相同的(只是一个1个字节类型,一些编译器充塞执行bool
只允许真/假值).但我没想到会有这样的问题!知道为什么吗?!
请注意,我知道bitsets并且对这里使用它们不感兴趣.
是的,bool
而且unsigned char
通常需要对自己的相同内存容量,但不会使vector<bool>
和vector<unsigned char>
一样的!
vector<bool>
标准给予了非常非常特殊的处理,以便尽可能地接近元素(20世纪90年代的人认为这是聪明的,因为bool
只有两个状态之一),结果就是你所看到的:它的元素是不可寻址的.
避免!