以前は、アクセスしたアイテムのディープstd::vector::operator[]
コピーが取得されると考えていましたが、必ずしもそうではないようです。少なくとも、次のテスト コードでは異なる結果が得られます。vector<bool>
#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 でコンパイルされたソース コード):
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 -------------------------------
v[0]
代入後もx = newValue
以前の値と同じになると予想していましたが、そうではないようです。何故ですか?なぜvector<bool>
特別なのですか?