std::vector of references

后端 未结 3 786
后悔当初
后悔当初 2020-12-08 08:10

I have such problem: I have class Foo, and if have some objects of this class,

Foo a();

I need to put this object to 2 differ

相关标签:
3条回答
  • 2020-12-08 08:16

    Instead of keeping Foo as object keep as pointer to object Foo, e.g.

    std::vector<Foo *> vA, vB;
    

    and manage allocations and deallocations carefully to avoid memory leakage (Allocating but not deallocating when done). If you allocate one Foo object and keep the pointer in both vA and vB , then you are keeping essentially same object in both through the pointer. Otherwise you may use smart pointer (better) refer:

    What is a smart pointer and when should I use one?

    0 讨论(0)
  • 2020-12-08 08:27

    You need a vector of references. And since you specify that you need to use std::vector, then the correct thing to do is wrap your objects in the std::reference_wrapper. This page from C++ reference should explain it nicely:

    vector<reference_wrapper<Foo>> vA, vB;
    vA.push_back(a);
    vB.push_back(a);    // puts 'a' into both vectors
    
    // make changes to 'a'
    // use .get() to get the referenced object in the elements of your vector
    // vA[0].get() == vB[0].get()
    
    0 讨论(0)
  • 2020-12-08 08:34

    There are some possibilities:

    1. Store a vector of pointers (use if your vectors share ownership of the pointers):

      std::vector<std::shared_ptr<Foo>> vA, vB;
      
    2. Store a vector of wrapped references (use if the vectors do not share ownership of the pointers, and you know the object referenced are valid past the lifetime of the vectors):

      std::vector<std::reference_wrapper<Foo>> vA, vB;
      
    3. Store a vector of raw pointers (use if your vectors do not share ownership of the pointers, and/or the pointers stored may change depending on other factors):

      std::vector<Foo*> vA, vB;
      

      This is common for observation, keeping track of allocations, etc. The usual caveats for raw pointers apply: Do not use the pointers to access the objects after the end of their life time.

    4. Store a vector of std::unique_ptr that wrap the objects (use if your vectors want to handover the ownership of the pointers in which case the lifetime of the referenced objects are governed by the rules of std::unique_ptr class):

      std::vector<std::unique_ptr<Foo>> vA, vB;
      
    0 讨论(0)
提交回复
热议问题