Search code examples
c++boostiteratorshared-ptr

How to cast vector<T>::iterator (on the heap) as shared_ptr<T>


I'm afraid that each existing question/answer in this area seems to be subtly different:

I have a shared_ptr<vector<Point>> profile which is looped using an iterator. I would like to preserve a shared_ptr<Point> outside the loop for various purposes, but am struggling with the syntax. Please can you advise?

Here is a basic example:

shared_ptr<Point> peak;
for (vector<Point>::iterator point=profile->begin(); point!=profile->end(); point++)
{
    ...
    peak = shared_ptr<Point>(*point); // fails
    ...
}

N.B. I suppose that using a plain reference/pointer to the Point would be simple enough, but I am trying to avoid this, particularly when the heap is involved. I also realise that I could use indexes in this case, but this would be less transferable between container classes.


Solution

  • What you need is shared_ptr<vector<shared_ptr<Point>>> if you want to safely pass around shared_ptr<Point>'s

    The problem you have is that if your shared_ptr<vector<Point>> goes out of scope, any shared_ptr<Point> constructed from members of the vector will be pointing to invalid memory.

    On the flip side, if your newly created shared_ptr<Point> went out of scope, you'd then be trying to deallocate memory managed by the vector which isn't a good thing!