a vector of references

closed account (SECMoG1T)
Hi , I got a question about vectors, is it possible to have a vector of references to objects

1
2
3
4
5
6
7
8
9
10
11
12
13
14
  #include <vector>

  struct obj
  {
    obj(int dt): data(dt) {}
    int data;
  };
   
  int main ()
  {
   vector<obj&> vec{1, 2, 3, 4, 5, 6, 7}//is these possible? 
  
  }
 


I can't get this working
> is it possible to have a vector of references to objects

No.

Vectors contain objects. (An object is a region of storage that has a size, a type, and a lifetime.)
References are not objects. (A reference has no address of its own; it may not occupy any storage at all.)

std::reference_wrapper is a class template that wraps a reference in a copyable, assignable object. It is frequently used as a mechanism to store references inside standard containers (like std::vector) which cannot normally hold references.
http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper

There is an example at the bottom of the page.
closed account (SECMoG1T)
Thanks you very much , I used the reference::wrapper n it's workin' great, I din't know vectors couldn't work with references, thank you @JLBorges
Topic archived. No new replies allowed.