Search code examples
c++referenceiteratorc++20

C++ : if iterator is an object, why can't it be initialized to a reference iterator?


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:

  1. v.begin() will return an iterator - which is actually an object
  2. v_i1 a variable is initialized with the iterator return from begin(). No issue
  3. 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.


Solution

  • 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();
    }