It seems I don't fully understand how exactly C++ references work. Trying to run following snippet:
std::vector<int> test{1,2,3};
int& ref = test.back();
auto lambda = [&ref, &test](){
std::cout << "inside lambda " << ref << std::endl;
ref += 1;
for (auto&v : test)
std::cout << v << " ";
};
lambda();
lambda();
lambda();
test.push_back(5);
lambda();
lambda();
lambda();
return 0;
}
And got this result:
inside lambda 3
1 2 4
inside lambda 4
1 2 5
inside lambda 5
1 2 6
inside lambda 6
1 2 6 5
inside lambda 7
1 2 6 5
inside lambda 8
1 2 6 5
Why after push_back is done, none of vector elements is incremented? And where ref points to from this moment?
Aucun commentaire:
Enregistrer un commentaire