vector<vector<string> > test
for example.
g++, you can do
test.reserve(10);
test[0] = othervector;
test[9] = othervector;
It doesn't crash. Theory says you shouldn't do it like that because you are assigning a vector to a chunk of memory that believes it is a vector.
But it works just like the next one:
#include <string>
#include <vector>
#include <iostream>
using namespace std;
int main(){
vector<string> first_vector;
vector<string> &second_vector = *(vector<string>*)new char[sizeof(vector<string>)];
first_vector.push_back("whatever");
first_vector.push_back("whatever2");
first_vector.push_back("whatever3");
second_vector = first_vector;
cout << "0 " << second_vector[0] << " \n";
cout << "1 " << second_vector[1] << " \n";
cout << "2 " << second_vector[2] << " \n";
}
This looks to me like the assignment operator of a vector actually copies all, or at least enough fields of the vector implementation for this to work, rendering a perfectly valid vector in the uninitialized.
Well, this is clearly undefined behavior to me, only problem is that it works as expected, I found quite a lot of these in a codebase I'm currently inspecting.
Are there more cases like this one in the rest of the containers? Never seen one that looks so easy to make a mistake but that it actually works even if you make the mistake.
EDIT: This is not about how to do the above properly or complain about the compilers behavior, its trying to find similar issues easy to happen and really difficult to spot later, like this one.