I'd like to know why is this code legal:
std::vector<int>::iterator & foo(std::vector<int>::iterator & iter) {
return ++iter;
}
int main() {
std::vector<int> v = { 1,2,3,4 };
std::cout << *foo(v.begin()) << std::endl;
}
The function accept a non-const reference to an iterator, but I have not initialized any variables holding that iterator, I simply passed the result of v.begin() as a reference, but the function is able to increase its value, return it, and use the result to print an element of the vector:
Where is the iterator stored? I'm still learning C++ (Started around 3 weeks ago) so I'm a bit confused, but I have an "idea":
Is a temporary variable initialized just before the call, like when passing a literal to a function that accept a const reference (Example below)?
std::vector<int>::iterator & foo(std::vector<int>::iterator & iter) {
return ++iter;
}
int main() {
std::vector<int> v = { 1,2,3,4 };
std::vector<int>::iterator tempIter = v.begin();
std::cout << *foo(tempIter) << std::endl;
}
Thanks!