will using a shared_ptr on class instance members clean up the new’ed objects correctly when the owning “parent” drops out of scope? Like in the example below?
Code example below – so when the Family instance goes out of scope will it clean up/delete the people objects linked to in the map?
If so how can i confirm this? Are there tools i can use to show before and after – after showing no person object – and if i put the normal pointers back i should still see the person objects – thanks
class Family
{
private:
//std::map<int ,Person*> _people;
std::map<int ,std::tr1::shared_ptr<Person>> _people;
public:
void AddPerson(int age)
{
//_people[age] = new Person(age);
_people[age] = std::tr1::shared_ptr<Person>( new Person(age));
}
};
class Person
{
private:
int _age;
public:
Person(int age)
{
_age= age;
}
int GetName(){return _age;}
};
Go through it:
Familygoes out of scope,_peopleis destroyed, themapdestructor removes all it’s elements, which means that for each element, the destructor is called. Allshared_ptrSin the map decrement their reference count. If the reference count is now 0, the objects are destroyed. Although I don’t see why you would store a pointer (smart or not) in your example, I guess you have your reasons.