Search code examples
c++pointersc++11shared-ptrsmart-pointers

shared_ptr to std::vector of shared_ptr data destruction


Lets say I have a function which returns a smart pointer to a vector of smart pointers to some data.

shared_ptr<vector<shared_ptr<Data>> getVectorPtr();
auto vecPtr = getVectorPtr();

When vecPtr goes out of scope and is going to be destroyed do the shared_ptrs inside it also get deleted?

Just for knowledge: how does a smart pointer, internally, realizes it went out of scope?


Solution

  • When The outer shared pointer goes out of scope (and the reference count goes to zero), it destroys the vector. The vector in turns destroys its elements (the inner shared pointers). When the elements reference count goes to zero as well, the inner objects are destroyed, too.

    So in your case, destruction of inner elements depends on possible other references to them.