Search code examples
c++c++11vectorshared-ptr

Conditions for deletion of an std::shared_ptr


Lets say I have the following:

class Bar
{
    public:
        int i;
};

class Foo
{
    public:
        std::vector<std::shared_ptr<Bar>> vector;
};

class FooBar
{
    public:
        std::shared_ptr<Bar> myBar;
};

int main()
{
    Foo foo;
    FooBar foobar;

    foobar.myBar = std::make_shared<Bar>();

    foo.vector.push_back(foobar.myBar);

    foobar.myBar = nullptr;
}

Does both myBar and foo.vector.back() equal nullptr? Have they both been deleted? What would be the right way to do this? My endgoal is to be able to have a vector of pointers to objects, construct objects and put them into that vector from a different scope, then in the scope they were created in delete them and have them removed from the vector. My thought process is if I can somehow delete all instances of the pointer easily then I can just do a check each frame to remove the shared_ptr from the vector if it equals nullptr.


Solution

  • When you push_back you make a copy of what you insert, in this case the shared_ptr. So no, the object is not deleted because the copy of the shared_ptr still exists; as long as any shared_ptr still points to the object it is kept alive.

    What you're looking for I think is a weak_ptr. If you pull one of those from the vector you need to convert it to a shared_ptr before you can use it, and if that conversion fails you know the object was deleted.