Memory leak?

Will this code cause memory leak?
1
2
3
4
5
6
vector<ClassA*> list;
for(int i = 0; i < 5; ++i)
{
    ClassA *a = new ClassA;
    list.push_back(a);
}


Is this ok cause I think the memory can be still deleted with
delete list[3];
Or should this be done with something else?
Thx
Yes, that's a leak and yes, you can (should) delete with a simple delete list[i];
A rule of thumb could be that for every new in your code there should be a delete (this is not true for smart pointers though).
I think the question was whether or not he can still delete it from the vector - which is the case, so, in that part of the code no memory leak is caused.
it's technically not a leak until the list variable falls out of scope

(so if your chunk of code were enclosed by braces and included no other code, I would call it a leak)

otoh, given your OP code, if the list variable falls out of scope and you haven't copied its entries elsewhere and you haven't called delete on all the entries, then you have a memory leak

edit: a leak has occurred iff you can no longer call delete on the address
Last edited on
So that's not a leak when i can still destroy pointers from list but a is out of scope. Thx peeps.
Last edited on
Note that you should use a ptr_vector in this case, which takes care of object deletion automatically.

http://www.boost.org/doc/libs/1_46_1/libs/ptr_container/doc/ptr_vector.html
Do ptr_vector have any benefit compare to vector<unique_ptr>?
Thanks
None that I am aware of, so if C++0x can be used, vector<unique_ptr> is preferable.
Although, since the unique_ptr constructor is explicit, you can't write up_vec.push_back(new int);, but that's only a minor inconvenience.
Topic archived. No new replies allowed.