vendredi 26 janvier 2018

push_backs to a std::vector

Consider this attempt at push_backs to a std::vector of std::reference_wrappers:

#include <iostream>
#include <vector>
#include <functional>
int main()
{
  std::vector<int> v_i;
  std::vector<std::reference_wrapper<int>> s_i;
  for(int i=0;i<10;++i)
  {
    v_i.push_back(i);
    s_i.push_back(std::ref(v_i[i]));
  }
  std::cout<<v_i[0]<<std::endl;
  std::cout<<s_i[0].get()<<std::endl;
  return -1;
}

I expect the [] operator to return a reference to the i-th element of v, and from the possible implementation given here, we can reasonably assume that the std::reference_wrapper object that is appended to s_i holds a copy of the pointer that points to the correct address of v_i[i]. However, the output of the code above is

0
1980603512 //or some other random garbage value

So obviously, the std::reference_wrappers that are constructed inside the loop are pointing to temporary objects. Why does this happen, and what is the correct way of appending to s_i?

By the way, I am using g++ 5.4.0 (with the -std=c++0x flag).

Aucun commentaire:

Enregistrer un commentaire