【发布时间】: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;
}
【问题讨论】: