繁体   English   中英

指向std :: vector元素时的编译器错误 <bool> ?

[英]compiler error when pointing to an element of std::vector<bool>?

尝试使用std::vector<bool>我遇到了一个编译器错误,这对我来说非常令人惊讶。

简而言之,获取std::vector<unsigned char>元素的地址并将其分配给unsigned char指针:

std::vector<unsigned char> test(10);
unsigned char *pb = &test[0];

完美地工作,同时尝试使用std::vector<bool>导致编译器错误:

int main() {

    std::vector<bool> test(10);
    bool *pb = &test[0];    // line 4, compile error

    return 0;
}

在Visual Studio上,它表示如下内容:

std::vector bool cannot convert std::_Vb_reference<_Alloc> * to bool *

而键盘( 请参见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.

我认为boolunsigned char在内部都是相同的(只是1字节类型,有些编译器强制bool只允许true / false值)。 但是我没想到会有这样的问题! 知道为什么吗?

请注意,我知道位集,因此对在这里使用它们不感兴趣。

是的, boolunsigned char通常自己占用相同的内存量,但这不会使vector<bool>vector<unsigned char>相同!

vector<bool>进行了非常非常特殊的处理,以使其元素尽可能地紧凑(1990年代有人认为这很聪明,因为bool只有两个状态之一),结果是您已经看到:它的元素是不可寻址的。

避免!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM