简体   繁体   中英

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, ...)?

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 Clash es 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.

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