Jump to content
  • Advertisement
Sign in to follow this  

C++ STL list memory management question

This topic is 4610 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
Advertisement
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
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
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
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
@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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!