std ::参考矢量 [英] std::vector of references

查看:88
本文介绍了std ::参考矢量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的问题:我有 Foo 类,如果有此类的某些对象,则

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 different vectors:

std::vector<Foo> vA, vB;

,如果 a 中的 vA 应该在 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. 存储指针向量(如果指针的向量共享所有权,请使用):

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

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;
    


  • 这篇关于std ::参考矢量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆