I am new to C ++ 11 smart pointers and I am trying to use them effectively in a project. In my project, I have many functions that take a constant reference to vector of unique_ptr , perform some calculations on it and put some results in the returned parameter, for example:
void computeCoefficients(const vector<unique_ptr<Scalar>>& roots, vector<unique_ptr<Scalar>>& coeffs) { ... }
I use unique_ptr because the procedure that calls all of these functions is the sole owner of the objects in vector , and the functions simply “borrow” the objects to read them as input.
Now I'm trying to write a function that performs calculations on the different subsets of vector that it receives, and for this it needs to have different "versions" of vector containing these subsets, in order to go to another function that accepts the input vector<unique_ptr<Scalar>> . But the only way to get a subset of a vector is to make a copy of it - which is a problem because unique_ptr cannot be copied. I would like the code to look something like this:
void computeOnSet(const vector<unique_ptr<Scalar>>& set, unique_ptr<Scalar>& output) { ... } void computeOnAllSubsets(const vector<unique_ptr<Scalar>>& set, vector<unique_ptr<Scalar>>& outputs) { for(int i = 0; i < input.size(); i++) { auto subset = vector<unique_ptr<Scalar>>(set.begin(), set.begin()+i); subset.insert(subset.end(), set.begin()+i+1, set.end(); computeOnSubset(subset, outputs.at(i)); } }
Of course, this does not work. I could make it work if I replaced unique_ptr with shared_ptr s, but it has two problems:
- It would philosophically mean that I share the ownership of the set using the
computeOnSubsets function, and I do not; the caller remains the sole owner. (I read that shared_ptr means that you share the property with everything that has a copy of it). - This will lead to overhead for link counting even in places where I don’t need it, because it will force me to change the input parameter of all my methods to
vector<shared_ptr<Scalar>> .
All I want to do is make a temporary copy of the read-only pointer for the sole purpose of creating temporary read-only sub-vectors. Is there any way to do this? weak_ptr sounds like what I need (not owning a temporary pointer), but it can only be used with shared_ptr .
c ++ c ++ 11 stdvector unique-ptr shared-ptr
Edward
source share