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

transform vector of shared_ptr with non const elements to vector of shared_ptr with const elements

我有一个 class A 包含一个向量 shared_ptr<B>。 我对这个向量实施了 getter。 在某些情况下,最好确保 B 中的内容不会更改(将 B 设置为只读或常量引用)。

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

有没有办法用 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;
}

transform vector of shared_ptr with non const elements to vector of shared_ptr with const elements

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

您可以通过为 class.

实现自定义 const 迭代器来避免分配和复制向量的开销

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

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

请注意,该函数现在 return 不是引用,因为我们正在创建一个临时文件并 returning 它。