Pointers held in STL List
Quick question about storing pointers within a STL List.
Say I have a class
class A
{
A();
~A();
blah
}
and I create an STL list
std::list<A*> listOfA;
and in some function I add A's to this list
void addToList()
{
listOfA.push_back(new A());
}
Do I have to delete the memory held within the list when the program finishes?How is memory freed from STL list?
Thanks,
Edwin
Yeah thats what I thought.
That seems to put me in alot of bother, I think I'll look into smart pointers.
That seems to put me in alot of bother, I think I'll look into smart pointers.
If you use smart pointers, make sure to use a reference counted pointer of some kind, since auto_ptr isn't safe for use in containers.
This is probably a dumb quesiton, but do you actually need to use pointers here? (i.e., are you using polymorphism?)
This is probably a dumb quesiton, but do you actually need to use pointers here? (i.e., are you using polymorphism?)
No I'm not using polymorphism. I thought it was necessary to use std::list<T*> in this situtation also. As once I leave that function will the list keep a copy of my object T, even thought the original object is now out of scope?
The list will keep a copy of the object, yes. Not the original. Make sure you overload operator=() and the copy constructor too, unless your class is a POD (Plain Old Data) type (I.e. no pointers).
What does your class contain?
What does your class contain?
Quote:Original post by Broni
No I'm not using polymorphism. I thought it was necessary to use std::list<T*> in this situtation also. As once I leave that function will the list keep a copy of my object T, even thought the original object is now out of scope?
Standard containers keep a copy of their value type (whether that value is T or T*). As long as the list is in scope, it's contents are good.
Ok. So if I dont want to keep copys I can use T* instead of T, but I'll have to manually delete these objects- is that correct?
The list only cares about the type it's holding. If it's holding instances (not pointers) of A objects, it will make copies of them and make sure they get destroyed and all that stuff for you, no need to worry about anything.
If it's holding pointers to A objects, it will copy the pointers, and destroy the pointers (and by destroy I don't mean delete what they're pointing to), but the actual objects that the pointers are pointing to will be completely ignored by the list. It doesn't care about what the pointers are pointing to, all it cares about are the pointers themselves.
If it's holding pointers to A objects, it will copy the pointers, and destroy the pointers (and by destroy I don't mean delete what they're pointing to), but the actual objects that the pointers are pointing to will be completely ignored by the list. It doesn't care about what the pointers are pointing to, all it cares about are the pointers themselves.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement