Do I have to manually reset inner shared_ptrs (shared_ptrs as members of a class)

71 Views Asked by At

Lets say I have:

class InnerClass { };

class MyClass {
public:
    std::shared_ptr<InnerClass> innerSharedPtr;
};

void main() {
    std::shared_ptr<MyClass> mrSharedPtr = std::make_shared<MyClass>();
}

If I want to reset mrSharedPtr, do I need to reset it's shared_ptr members?

mrSharedPtr->innerSharedPtr.reset();
mrSharedPtr.reset();

If I mrSharedPtr.reset(), it reduces reference count to 0, but does that reduce innerSharedPtr to 0? if not does that mean innerSharedPtr remains in memory?

There's no way to check the reference count after resetting

1

There are 1 best solutions below

0
463035818_is_not_an_ai On

std::shared_ptr::reset (from cppreference):

If *this already owns an object and it is the last shared_ptr owning it, the object is destroyed through the owned deleter.

When the MyClass instance is destroyed, part of that is to destroy the innerSharedPtr member. When this shared_ptr was the last shared pointer to that InnerClass, that instance will be destroyed as well.

There is no need to call mrSharedPtr->innerSharedPtr.reset(); before mrSharedPtr.reset();.