0

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?

nin
  • 48
  • 7
  • 4
    "how does it internally realize it went out of scope?" Its destructor is called – Creris Jul 23 '15 at 19:28
  • 1
    it has a counter (reference count). Everytime it goes out of scope it decreases it and when the count is 0 it calls the destructor. If you pass it by value it increases the count, if you pass it by reference the count stays the same –  Jul 23 '15 at 19:29
  • Thanks, should have figured that out. When the smart pointer goes out of scope its destructor gets called and it will handle the ref count and if needed will delete the data. – nin Jul 23 '15 at 19:43

1 Answers1

1

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.

Manuel Barbe
  • 2,104
  • 16
  • 21
  • So If there's only one reference to the vector and its Data isn't referenced anywhere else (aside from the vector itself) then the vector's destruction will call the destructor of each of the shared_ptr pointing to Data, its ref count will reach 0 and the Data will be deleted. Thanks! – nin Jul 23 '15 at 19:47