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; }
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.
Yes. vector::erase destroys the removed object, which involves calling its destructor.
std::vector will not automatically de-allocate the memory, so your program will leak.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With