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

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

本文关键字:lt gt bool 编译器 vector std 元素 指向 错误      更新时间:2023-10-16

尝试使用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只允许真/假值)。但我没想到会有这样的问题!知道为什么吗?!

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

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

标准对vector<bool>进行了非常非常特殊的处理,以便尽可能接近地打包元素(1990 年代有人认为这会很聪明,因为bool只有两种状态之一),结果就是你所看到的:它的元素是不可寻址的。

避免!