Skip to main content
gamedev.net
🔒 Locked

Pointers and STL

Started by juglarx Apr 26, 2006 at 10:06 AM 4 replies 1.1k views
Original Post
juglarx
juglarx
if y have this std::map kPipeline; and then KBOX * kbox = new KBOX; kPipeline = kbox; delete kbox; i need to delete kPipeline at the end of my program with delete kPipeline; is that correct?? thanks in advance
DrEvil
DrEvil
no

KBOX * kbox = new KBOX;
kPipeline = kbox;
delete kbox;

you only have to delete the thing you new'd. after you are done with the container or when you are removing the element from the container. the code above is bad, cuz it leaves a bad pointer in the map.
BlueHabu
BlueHabu
Quote:
Original post by DrEvil
KBOX * kbox = new KBOX;
kPipeline = kbox;
delete kbox;


Isn't pointer after delete kbox in kPipline invalid making kPipeline->SomeMethod() an access violation?

I think you want to do delete kPipeline, for all i, when you want to clear the kPipeline. Not right after you add the object pointer to the map.



juglarx
juglarx
Quote:
Original post by BlueHabu
Quote:
Original post by DrEvil
KBOX * kbox = new KBOX;
kPipeline = kbox;
delete kbox;


Isn't pointer after delete kbox in kPipline invalid making kPipeline->SomeMethod() an access violation?

I think you want to do delete kPipeline, for all i, when you want to clear the kPipeline. Not right after you add the object pointer to the map.


ups! u'r right!
Palidine
Palidine
std::map<int,KBox*> kPipeline;void addKBOX(){    KBOX * kbox = new KBOX;    kPipeline = kbox;}//to be called when you are done with the kPipeline mapvoid freeAllMemory(){    std::map<int,KBox*>::iterator ite = kPipeline.end();    for ( std::map<int,KBox*>::iterator it = kPipeline.begin(); it != ite; ++it )    {        delete (*it).second;    }    kPipeline.clear();}
Zahlman
Zahlman
Or you could use Boost::ptr_map.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.