I want to store shared pointers to the Object
class in a vector:
Test code:
#include <vector>
#include <iostream>
#include <memory>
using namespace std; // only for brevity
class Object
{
public:
int n;
Object(int n) : n(n) { cout << "Object(" << n <<")\n"; }
~Object() { cout << "~Object(" << n << "))\n"; n = 0xdddddddd; }
};
void Test()
{
std::shared_ptr<Object> p1(make_shared<Object>(Object(123)));
std::vector<shared_ptr<Object>> v;
cout << "before push_back\n";
v.push_back(std::make_shared<Object>(Object(2)));
v.push_back(p1);
cout << "after push_back\n";
cout << "Vector content:\n";
for (auto& p : v)
cout << " " << p->n << "\n"; ;
}
int main()
{
Test();
cout << "after Test()\n";
}
The output is
Object(123)
~Object(123)) <<< why is the destructor called here?
before push_back
Object(2)
~Object(2)) <<< why is the destructor called here?
after push_back
Vector content:
2
123
~Object(2)) <<< destructor called again
~Object(123))
after Test()
I don't understand why the destructors are called twice.
OTOH the vector content is what I want.