I have a class:
class X {
vector<shared_ptr<T>> v_;
public:
vector<shared_ptr<const T>> getTs() { return v_; }
};
It has a vector of shared_ptr of type T. For some reason, it needs to expose a method to return this vector. However, I don’t want the content of the vector to be modified, neither are the objects being pointed to. So I need to return a vector of shared_ptr<const T>.
My question is, is there any efficient way to achieve this? If I simply return it, it works, but it needs to reconstruct a vector, which is kind of expensive.
Thanks.
You can not do that directly – but you can define “views” on your container that let you do something very similar, if you want to make sure that your pointees are const:
A simple transform iterator adapter / transformed range might do the trick as well, I just used this to illustrate the point.