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:
- v.begin() will return an iterator - which is actually an object
- v_i1 a variable is initialized with the iterator return from begin(). No issue
- If v.begin() returns an iterator (object here??), why can't it be assigned to reference v_i2? Is it because v.begin() return a rvalue?
Thanks for helping me to understand better.
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:
- v.begin() will return an iterator - which is actually an object
- v_i1 a variable is initialized with the iterator return from begin(). No issue
- If v.begin() returns an iterator (object here??), why can't it be assigned to reference v_i2? Is it because v.begin() return a rvalue?
Thanks for helping me to understand better.
Share Improve this question edited Nov 21, 2024 at 4:10 yapkm01 asked Nov 20, 2024 at 5:33 yapkm01yapkm01 3,7819 gold badges40 silver badges67 bronze badges 3 |1 Answer
Reset to default 2Non 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();
}
v.begin()
returns prvalue, so you should usevector <int>::iterator&&
. – 康桓瑋 Commented Nov 20, 2024 at 5:43to_string()
returns an string object which is prvalue. – 康桓瑋 Commented Nov 20, 2024 at 5:54