0

How to initialize a vector of reference_wrapper member variable in a class. I have tried to initialize with a vector in constructor initialisation_list.

 class Test
    {
    public:
        Test(std::vector<int> vec) :vec_r(begin(vec), end(vec)) // not working
        {
        }
        std::vector<std::reference_wrapper<int>> vec_r; //member variable
    };

    int main()
    {
        std::vector<int> v{ 1,2,3 };
        Test testObj(v);
        
        std::cout << testObj.vec_r[0].get() <<'\n'; // prints unintialised value 
        std::cout << testObj.vec_r[1].get() <<'\n'; // prints unintialised value 
        std::cout << testObj.vec_r[2].get() <<'\n'; // prints unintialised value 
        return 0;
    }

Is there any other way to initialize a 'reference_wrapper' vector in a class?

Arun AC
  • 417
  • 7
  • 17
  • 1
    Why not just store a reference to the entire vector? A `const vector&` member would give you access to all of the elements but stop you from being able to modify the vector itself. – NathanOliver Mar 22 '22 at 13:58
  • 2
    The argument variable `vec` is passed *by value*. The vector and all data in it will cease to exist once the constructor returns. Saving references to data in the vector is pointless and wrong. – Some programmer dude Mar 22 '22 at 14:01
  • On another and unrelated note, why do you use `printf` for your printing? Why not e.g. `std::cout << testObj.vec_r[0] << '\n';`? – Some programmer dude Mar 22 '22 at 14:06
  • So you don't actually need a vector of reference wrappers? The code you have currently should work, it's just that `vec` wasn't passed by reference so `vec_r` is storing references to objects that no longer exist. – NathanOliver Mar 22 '22 at 14:25
  • @NathanOliver, if I change 'vec' as reference_wrapper vector, then this code works. Also, if 'vec_r' is not a member variable, std::vector> vec_r(begin(vec), end(vec)); works. – Arun AC Mar 22 '22 at 14:58
  • I think that @NathanOliver meant that you should make both the `vec` argument *and* the `vec_r` member variables references. So that `vec_r` reference the original vector `v` from the `main` function. I.e. `Test(std::vector const& vec) : vec_r(vec) {}` and then `std::vector const& vec_r;` This will also remove the unnecessary copy of `v` to the argument variable `vec`. – Some programmer dude Mar 23 '22 at 06:51

0 Answers0