std::引用向量

2021-12-21 00:00:00 vector c++ stl

我有这样的问题:我有 Foo 类,如果有这个类的一些对象,

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

Foo a();

我需要把这个对象放到 2 个不同的向量中:

I need to put this object to 2 different vectors:

std::vector<Foo> vA, vB;

如果avA中发生变化,它应该在vB、向量vA中发生变化vB 可以不同,但??它们可以具有相同的对象.我知道可以使用 Boost,但我不能使用 Boost.

and if a changes in vA it should be changed in vB, vectors vA and vB can be different, but they can have same objects. I know that it is possible to do with Boost, but I can't use Boost.

推荐答案

有一些可能性:

  1. 存储一个指针向量(如果您的向量共享指针的所有权,则使用):

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

  • 存储包装引用的向量(如果向量不共享指针的所有权,并且您知道引用的对象在生命周期后有效,则使用向量):

  • 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;
    

  • 存储原始指针向量(如果您的向量不共享指针的所有权,和/或存储的指针可能会因其他因素而变化,请使用):

  • 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.

    存储包装对象的 std::unique_ptr 向量(如果您的向量想要移交指针的所有权,在这种情况下生命周期为被引用对象的数量由 std::unique_ptr 类的规则控制):

    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;
    

  • 相关文章