简体   繁体   中英

How to have reference vector as a class member?

I have a class that holds a vector. I want it so that if the original vector is modified, then the class member vector will also be modified. Ie the class member vector is a reference to the original vector:

#include <iostream>
#include <string>
#include <vector>
using namespace std;

class Entity {
    public:
    int x;
    Entity() {}
    Entity(int y) : x(y) {}
};

class Me {
    public:
    vector<Entity> vec;
};

Me me;

int main()
{
  Entity e1(1);
  Entity e2(2);
  vector<Entity> vec;
  vec.push_back(e1);
  vec.push_back(e2);
  me.vec = vec;
  
  me.vec[0].x = 5;
  
  cout << vec[0].x << endl;
  return 0;
}

This outputs 1 when I want it to output 5.

In your snippet, the two vector s are independent instances (apart from one being initialized by the other). With this,

class Me {
    public:
    vector<Entity> vec;
};

/* ... */

me.vec = vec;

you copy the content of vec into me.vec and any modification of either me.vec or vec don't affect the other. What you want is this:

class Me {
    public:
    vector<Entity> *vec; // now a pointer to a vector
};

/* ... */

me.vec = &vec; // initialize the pointer with the address of vec

Now, any changes to vec will be reflected by an access through me.vec . Note that this ships with the necessity to take care of the pointer - it can be nullptr , in which case you must not dereference it. And it can change the location it points to, which can be error prone. As an alternative, consider storing a reference to a vector in Me . A reference has no null-state and can only be bound once. On the flip side, you have to initialize Me instances with an existing vector instance.

You have two options here...

Use a vector reference

Have the class hold a vector<Entity> & , or a vector reference . This will require you to pass the vector you're referencing to the class at the time of creation. That could look like:

class Me {
    public:
    vector<Entity> &vec;
    Me(vector<Entity> &v): vec(v) { }
};

// ...

int main() {
    vector<Entity> vec;
    Me me(vec);
    // ...
    
    me.vec[0].x = 5;

    cout << vec[0].x << endl;
}

Use pointers

If it didn't occur to you to use pointers, then I'd say that you should probably avoid them here, as you likely don't have the understanding to implement them safely.

That being said, if you're interested, I'd look into Smart Pointers .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM