jeudi 17 août 2017

Vectors, iterators and their addresses

Consider the following piece of code:

using std::vector;

vector<vector<int>::iterator*> v;
vector<int> A{1,2,3,4};
vector<vector<int>::iterator> tmp(4);

int i=-1;
for (auto it=A.begin(); it!=A.end(); ++it) {
    tmp[++i]=it, v.push_back(&tmp[i]);
}

for (auto& x: v)
    std::cout<<**x<<" ";

This, when compiled with GCC 6.4.0 on MacOS 10.12.5, produces the expected output 1 2 3 4.

But, if we modify the above code slightly, like this:

using std::vector;

vector<vector<int>::iterator*> v;
vector<int> A{1,2,3,4};
vector<vector<int>::iterator> tmp;

for (auto it=A.begin(); it!=A.end(); ++it) {
    tmp.push_back(it), v.push_back(&tmp.back());
}

for (auto& x: v)
    std::cout<<**x<<" ";

It throws SIGSEGV. Why does this happen? Is even the behavior of first code implementation dependent/undefined, and I was just lucky that it worked?

Aucun commentaire:

Enregistrer un commentaire