vector< bool> :: operator []行为不当? [英] vector<bool>::operator[] misbehavior?
问题描述
Possible Duplicate:
Why vector<bool>::reference doesn’t return reference to bool?
我曾经认为,使用std::vector::operator[]
可以获取所访问项目的深副本,但似乎并非总是如此.至少,对于vector<bool>
,以下测试代码将给出不同的结果:
I used to think that with std::vector::operator[]
we get deep copies of the accessed item, but it seems that it is not always true. At least, with vector<bool>
the following test code gives a different result:
#include <iostream>
#include <vector>
using namespace std;
template <typename T>
void Test(const T& oldValue, const T& newValue, const char* message)
{
cout << message << '\n';
vector<T> v;
v.push_back(oldValue);
cout << " before: v[0] = " << v[0] << '\n';
// Should be a deep-copy (?)
auto x = v[0];
x = newValue;
cout << " after: v[0] = " << v[0] << '\n';
cout << "-------------------------------\n";
}
int main()
{
Test<int>(10, 20, "Testing vector<int>");
Test<double>(3.14, 6.28, "Testing vector<double>");
Test<bool>(true, false, "Testing vector<bool>");
}
输出(使用VC10/VS2010 SP1编译的源代码):
Output (source code compiled with VC10/VS2010 SP1):
Testing vector<int>
before: v[0] = 10
after: v[0] = 10
-------------------------------
Testing vector<double>
before: v[0] = 3.14
after: v[0] = 3.14
-------------------------------
Testing vector<bool>
before: v[0] = 1
after: v[0] = 0
-------------------------------
我希望x = newValue
赋值之后的v[0]
仍等于其先前的值,但这似乎不正确.
这是为什么?
为什么vector<bool>
很特别?
I would have expected that v[0]
after the x = newValue
assignment would still be equal to its previous value, but this seems not true.
Why is that?
Why is vector<bool>
special?
推荐答案
vector<bool>::operator[]
既不产生bool
也不引用bool
.它仅返回一个有点像参考对象的代理对象.这是因为没有对单个位的引用,并且vector<bool>
实际上以压缩方式存储了bool
.因此,通过使用auto
,您仅创建了该引用类对象的副本.问题是C ++不知道该对象充当引用.您必须在此处强制将衰减到值",方法是将auto
替换为T
.
vector<bool>::operator[]
neither yields a bool
nor a reference to a bool
. It just returns a little proxy object that acts like a reference. This is because there are no references to single bits and vector<bool>
actually stores the bool
s in a compressed way. So by using auto
you just created a copy of that reference-like object. The problem is that C++ does not know that this object acts as a reference. You have to force the "decay to a value" here by replacing auto
with T
.
这篇关于vector< bool> :: operator []行为不当?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!