【发布时间】:2017-04-18 03:46:43
【问题描述】:
尝试使用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 *
虽然键盘 (see example at 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.
我认为 bool 和 unsigned char 在内部是相同的(只是一个 1 字节类型,有一些编译器的东西强制 bool 只允许真/假值)。但我没想到会出现这样的问题!知道为什么吗?!
请注意,我知道位集,但对在这里使用它们不感兴趣。
【问题讨论】:
-
另一方面,我更喜欢使用迭代器而不是运算符的地址。使用迭代器可以提供更好的可扩展设计。
-
@YogeshSajanikar 这在这里很不合时宜,但我首先看到迭代器是不可读的(在
for (int i=0; i<10; i++) a[i]=0;和for (std::vector<my_type>::iterator it=a.begin(); it!=a.end(); ++it) *it=0之间,第一个是 much 更具可读性) 并且我猜它们会导致性能下降(尤其是在使用所有不同检查等进行调试时),这对于像在内存中的给定位置放置/访问值这样简单的事情来说是一种痛苦。它们可能对其他包含(std::map 等)有用,但对于 std::vectors,我只是讨厌它们。 ;)