Search code examples
c++shared-ptrresetsmart-pointersstdvector

Will clear call reset on shared smart pointer


I have recently changed my raw pointer to use std::shared_ptr within a container like this:

std::vector<std::shared_ptr<AbstractPathContainer>> mGeneratedPaths;

When i call clear() on this container, will it call reset() method on each std::shared_ptr within it?


Solution

  • No, it will call the destructors. Destructors will decrease reference count for each smart pointer, if it brings to 0 then destructor calls to free function (by default this is delete wrapper). So if you did something like:

    std::vector<std::shared_ptr<AbstractPathContainer>> mGeneratedPaths ({c1, std::shared_ptr<AbstractPathContainer>(new AbstractPathContainerImpl())  });
    std::shared_ptr<AbstractPathContainer> smartRef = mGeneratedPaths[0];
     mGeneratedPaths.clear();
    

    smartRef will not be removed from heap.