M
Mike
Hello, I hope everybody had a good New Year.
I have a class that looks like the following:
class Foo {
public:
Foo();
~Foo() {} // Destructor is defined.
....
private:
std::vector<Bar*> _list1;
std::vector<Bar*> _list2;
....
};
As my program runs, _list1 and _list2 are populated as follows:
Bar* bar = new Bar();
_list1.push_back(bar);
_list2.push_back(bar);
In general, _list2 is a subset of _list1, so it isn't redundant.
My question is, what do I need to put in the destructor of Foo to
correctly delete these vectors? When Foo is deleted, I want all the
Bars contained in the two vectors to be deleted as well.
As I understand it, because I didn't initialize the vectors with the
new keyword, they are automatically deleted along with Foo (hence the
empty destructor). However, the destructor for std::vector
automatically calls the destructor of all of its elements. Let's say
_list1 is deleted first, this means _list2 is full of dangling
pointers, and deleting _list2 in the same fashion would be bad.
Thanks for your help,
Michael
I have a class that looks like the following:
class Foo {
public:
Foo();
~Foo() {} // Destructor is defined.
....
private:
std::vector<Bar*> _list1;
std::vector<Bar*> _list2;
....
};
As my program runs, _list1 and _list2 are populated as follows:
Bar* bar = new Bar();
_list1.push_back(bar);
_list2.push_back(bar);
In general, _list2 is a subset of _list1, so it isn't redundant.
My question is, what do I need to put in the destructor of Foo to
correctly delete these vectors? When Foo is deleted, I want all the
Bars contained in the two vectors to be deleted as well.
As I understand it, because I didn't initialize the vectors with the
new keyword, they are automatically deleted along with Foo (hence the
empty destructor). However, the destructor for std::vector
automatically calls the destructor of all of its elements. Let's say
_list1 is deleted first, this means _list2 is full of dangling
pointers, and deleting _list2 in the same fashion would be bad.
Thanks for your help,
Michael