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. <
The problem arises when the push_back
adds a copy of the shared_ptr
to the vector, leaving the original dangling until main exists. If you don't make the shared_ptr in main scope, the problem does not happen. Just avoid making the shared_ptr in main scope. Make it as a temporary right in the push_back
call.
Output is now:
constructor
I am almost there
destructor
I am here
New code:
#include
#include
#include
using namespace std;
class A
{
public:
A(){cout << "constructor" << endl;};
~A(){cout << "destructor" << endl;};
};
int main( )
{
vector > test;
test.push_back(shared_ptr(new A));
cout << "I am almost there" << endl;
test.clear();
cout << "I am here" << endl;
return 0;
}