J Doe.
J Doe.

Reputation: 5

Passing a objects from a vector to another class

I have 3 classes:

class User{
}

class Main{
public:
   void AddClash(){
       clash.push(Clash(...))
   }
private:
   std::vector<User> users;
   std::vector<Clash> clash;
}

class Clash{
public:
   //constructor
private:
   std::array<...,2> users;
}

I would like to have a method in the Main class, which will create a Clash object with a field that points to two objects from std::vector users in Main class.

What is the proper way to do that (pointer, std::reference_wrapper, std::shared_ptr, ...)?

Upvotes: 0

Views: 157

Answers (1)

Quentin
Quentin

Reputation: 63134

You're going to face the problem that std::vector displaces its content when it needs to grow, invalidating any pointer, reference or iterator in the process.

Thus, unless you know for sure that nothing will be pushed into your users vector while the Clashes are alive, you need to either :

  • Keep an index (std::size_t)into the vector. But you'll also need a reference to the vector itself, so you can access you object via vec[idx].

  • Add an indirection : make users an std::vector<std::unique_ptr<User>> (or shared_ptr, depending on your design). Then the User objects themselves won't ever move around.

Upvotes: 1

Related Questions