本文介绍了C ++: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 class):

    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;
    


  • 这篇关于C ++:std ::引用的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    08-18 13:49