Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vector of shared pointers , memory problems after clearing the vector

I realized that after calling vector.clear() which hold shared pointers, the destructors of the object which own by shared_ptr is not being released.

Code example can be seen below . Even vector.clear() being called, destructor called after shared pointer goes beyond the scope.My question is - do I have to delete all smart pointers inside the vector manually by resetting them? Is there any easier way that you can advice ?

Output :     constructor I am here destructor  Code:  #include <vector> #include <iostream> #include <memory>  using namespace std;  class A { public:     A(){cout << "constructor" << endl;};     ~A(){cout << "destructor"  << endl;}; };  int main( ) {     shared_ptr<A> sharedptr (new A);     std::vector<shared_ptr<A> > test;     test.push_back(sharedptr);      test.clear();     cout << "I am here" << endl; } 
like image 653
Kadir Erdem Demir Avatar asked Oct 12 '13 13:10

Kadir Erdem Demir


People also ask

What happens when a shared pointer goes out of scope?

The smart pointer has an internal counter which is decreased each time that a std::shared_ptr , pointing to the same resource, goes out of scope – this technique is called reference counting. When the last shared pointer is destroyed, the counter goes to zero, and the memory is deallocated.

Does vector erase delete pointers?

Yes. vector::erase destroys the removed object, which involves calling its destructor.

Does vector automatically deallocate memory?

std::vector will not automatically de-allocate the memory, so your program will leak.

How is vector memory stored?

Vectors are assigned memory in blocks of contiguous locations. When the memory allocated for the vector falls short of storing new elements, a new memory block is allocated to vector and all elements are copied from the old location to the new location.


1 Answers

you have two copies of shared_ptr<A> in this case, one is the sharedptr variable and the other as an element in the vector.

do this instead

test.push_back(std::move(sharedptr)); 

note now the original sharedptr has it's internal moved and no longer usable. The other thing is don't do anything at all, this is a perfectly valid usage of of shared_ptr and sharedptr will clean up itself after it goes out of scope.

like image 67
yngccc Avatar answered Sep 22 '22 14:09

yngccc