I'm trying to insert a copy of an existing vector
element to double it up. The following code worked in previous versions but fails in Visual Studio 2010.
#include <iostream>
#include <vector>
using namespace std;
int main(int argc, char* argv[])
{
vector<int> test;
test.push_back(1);
test.push_back(2);
test.insert(test.begin(), test[0]);
cout << test[0] << " " << test[1] << " " << test[2] << endl;
return 0;
}
Output is -17891602 1 2
, expected 1 1 2
.
I've figured out why it's happening - the vector is being reallocated, and the reference becomes invalid before it's copied to the insertion point. The older Visual Studio apparently did things in a different order, thus proving that one possible outcome of undefined behavior is to work correctly and also proving that it's never something you should rely on.
I've come up with two different ways to fix this problem. One is to use reserve
to make sure that no reallocation takes place:
test.reserve(test.size() + 1);
test.insert(test.begin(), test[0]);
The other is to make a copy from the reference so that there's no dependency on the reference remaining valid:
template<typename T>
T make_copy(const T & original)
{
return original;
}
test.insert(test.begin(), make_copy(test[0]));
Although both work, neither one feels like a natural solution. Is there something I'm missing?