Re: Deleting Vectors that Point to the Same Objects
On Jan 5, 5:55 am, Mike <westplas...@gmail.com> wrote:
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.
Just a nit, but there aren't any Bar's in your vectors. Just
pointers to Bar's.
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.
Yes. And the destructor of a pointer is a no-op.
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.
There won't be any dangling pointers unless you create them.
There will be a memory leak, however, unless you delete
everything you've new'ed. If _list2 really is a pure subset,
you can just delete everything in _list1. Otherwise, it's more
complicated---the simplest solution is to do what others have
suggested, use boost::shared_ptr. But it's also possible to
sort the two vectors, then merge them, removing duplicates, and
delete the set resulting from the merge. (It's not as
complicated as it sounds, but it's still a lot more work than
using boost::shared_ptr.)
--
James Kanze