Sign in to follow this  
wiseduck

C++ STL list memory management question

Recommended Posts

wiseduck    138
Hi there! I am using a lot of STL list in my C++ codes. But I could not find information on memory management with it. The question is: when I remove an object from the list, is the object deleted from memory or only the pointer in the list gets deleted? ex:
std::list<T> lista;

for(int i=0; i<10; i++)
    lista.push_back(*new T());

std::list<T>::iterator iter = lista.begin();

lista.erase(iter);
The first element gets out of the list. But does ig gets out of memory or should I create a pointer to it before erase()'ing and delete it?

Share this post


Link to post
Share on other sites
Telastyn    3777
STL containers only clean up the memory stored in them, in a pointer's case the 4 bytes [or however large] the address takes, not the new'd T().

Share this post


Link to post
Share on other sites
wiseduck    138
But in this exemple mine, the list contains T objects, not T pointers. The new has a * before it. But, so it deletes the the object?

PS: How to put code box that don't break '<' and '>' characters?

Share this post


Link to post
Share on other sites
Boku San    428
Don't mean to derail the thread...could someone explain the purpose/behavior of dereferencing the new operator (*new)?

I can't say I've seen it before, and it looks like it's nonstandard.

If someone could clear that up, it'd be great.

Share this post


Link to post
Share on other sites
nprz    692
When you push the object on the list, I think it would make a copy of it, so creating a dynamic object T, and (without keeping the track of the address) putting a copy of it in the list, I think you are leaking memory right at that point.

why not:
lista.push_back(T());
instead?
Either that or keep track of pointers and delete it before erasing from the list.

Share this post


Link to post
Share on other sites
wiseduck    138
@Boku San:
This kind of code compiled for me in g++ several times, and worked as expected (not considering the possibles memory leaks).

@nprz:
I wrote code this way cause I come from 2 years of Java programing. I didn't know the possibilitie of calling constructor this way. If it is really possible, it is indeed the best way to code. Bu I fail to see the practical differences from your code to mine.

edit: I read again, now I understood the difference.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this