【问题标题】:transform vector of shared_ptr with non const elements to vector of shared_ptr with const elements将带有非 const 元素的 shared_ptr 向量转换为带有 const 元素的 shared_ptr 向量
【发布时间】:2020-11-19 00:49:48
【问题描述】:

我有一个类A,其中包含shared_ptr<B> 的向量。 我为这个向量实现了一个吸气剂。 在某些情况下,最好确保B 中的内容不会改变(使 B 只读或 const 引用)。

如果我不使用vector<shared_ptr<B>> 而是使用vector<B>,我可以简单地编写两个getter,一个返回一个const 引用(只读),一个只返回一个引用(可以操作)。 #

有没有办法用vector<shared_ptr<B>> 做同样的事情?

也许这段代码更容易理解问题:

#include <vector>
#include <memory>
using namespace std;

class B{
public:
    explicit B(int i) : i_{i} {}
    void set_i(int i){i_ = i;}
private:
    int i_ = 0;
};

class A{
public:
    const vector<shared_ptr<B>> &get_vb(){return vb;}
    // const vector<shared_ptr<const B>> &get_vb_const(){return vb;} // I would like to return a const vector with const elements in some cases 
private:
    vector<shared_ptr<B>> vb{make_shared<B>(1), make_shared<B>(10), make_shared<B>(100)};
};

int main() {
    A a;
    const auto &vb = a.get_vb();
    vb[0]->set_i(2);
    
    // const auto &vb_const = a.get_vb_const(); // somehow I would like to gain this vector without being able to modify the elements
    // vb_const[0]->set_i(2); // should throw error
    
    return 0;
}

【问题讨论】:

    标签: c++ pointers constants


    【解决方案1】:

    将带有非 const 元素的 shared_ptr 向量转换为带有 const 元素的 shared_ptr 向量

    您可以使用接受一对迭代器的向量的构造函数来执行转换。

    您可以通过为您的类实现自定义 const 迭代器来避免分配和复制向量的开销。

    【讨论】:

      【解决方案2】:

      您需要使用所需元素构造一个新向量:

          const vector<shared_ptr<const B>> get_vb_const() const { 
              return vector<shared_ptr<const B> > {vb.cbegin(), vb.cend()};
          }
      

      请注意,该函数现在不返回引用,因为我们正在创建一个临时对象并返回它。

      【讨论】:

        猜你喜欢
        • 2018-07-16
        • 2015-01-19
        • 1970-01-01
        • 2017-08-06
        • 1970-01-01
        • 2021-06-21
        • 1970-01-01
        • 2014-01-18
        • 2018-12-02
        相关资源
        最近更新 更多