Vector of shared pointers , memory problems after clearing the vector

Kadir Erdem Demir picture Kadir Erdem Demir · Oct 12, 2013 · Viewed 54k times · Source

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;
}

Answer

yngccc picture yngccc · Oct 12, 2013

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.