Supposedly we have the below:
// Example program
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector <int> v {1,2,3};
vector <int>::iterator v_i1 = v.begin();
vector <int>::iterator &v_i2 = v.begin(); // error out - initial value of reference to non-const must be an lvalue
}
Understanding:
Thanks for helping me to understand better.
Non const reference can't bind to rvalue returnrd by std::vector::begin()
. Make the reference to const.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
vector <int> v {1,2,3};
vector <int>::iterator v_i1 = v.begin();
const vector <int>::iterator &v_i2 = v.begin();
}
Or, as commented, make it rvalue reference. The both prolong the temporary object' lifetime to the scope of the reference.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main() {
vector <int> v {1,2,3};
vector <int>::iterator v_i1 = v.begin();
const vector <int>::iterator &v_i2 = v.begin();
vector <int>::iterator &&v_i3 = v.begin();
}