Re: how to delete vectors that contain pointers to user-defined type objects
On Jun 15, 2:51 pm, dwightarmyofchampi...@hotmail.com wrote:
1. When we push_back a new Movie*, we are copying by value, so the new Mo=
vie parameter immediately goes out of scope. Is that a memory leak, and if =
so how do I fix it?
You copy the pointer by value; so you have two pointers to the same
memory (temoprarily). Then one pointer goes out of scope (but the
thing it's pointed to is still alive), no problem.
2. To delete the ten elements in movies, do I leave the iterator for loop=
where it is or do I put it in the Libraries destructor, or do both?
Well, if it's in both then you get a segfault because you called
'delete' twice on the same pointer. My answer would be 'neither'
though, see below
3. Are movies and this->video_library pointing to the same memory? I gues=
s that would be so, since that's what the line in the constructor is doing,=
pointing them both to the same address in memory. If so, how do I be sure =
that I'm deleting the elements being pointed to only once? If I change the =
Libraries destructor to the following:
That line in the constructor is creating a second vector
that's an exact copy of the first. You now have two vectors
each containing 10 pointers (and the pointers in one
point to the same memory as the pointers in the other).
This is OK per se, but you have to think carefully about how
is responsible for deleting the pointers.
Of course, boost::shared_ptr is one option; another is using
the VCL ownership mechanism, as other posters have suggested.
If you didn't like either of those, what you could do is put
all your "new"'d stuff into a container, which you then
"delete" at the end. For example:
vector<Movie *> all_movies;
Movie *temp = new Movie(....);
all_movies.push_back(temp);
movies.push_back(temp);
and then manipulate your movies with impunity, but don't tough
"all_movies". Then at the end of your program delete everything
in all_movies.
This setup doesn't work so well if you want to delete
movies before the end of the program; shared_ptr is
designed exactly for that.