0

Hello, i want to create a vector of pointers and delete them,but i am little confused whether my code is OKAY or not.

here's my code:

vector<Object*> SpriteList;

for(i=0;i<10;i++){
    Object* tempobj;
    tempobj=new Object();

    SpriteList.push_back(tempobj)
}

for(int i=0;i < (int) SpriteList.size();i++){
        delete SpriteList[i];
        SpriteList.erase(SpriteList.begin()+i);
}

is there any memory Leak??plz help...

4
Contributors
4
Replies
9
Views
4 Years
Discussion Span
Last Post by DeanMSands3
0

you could use smart pointer instead of the raw pointer

std::vector<std::auto_ptr<Object> > SpriteList;
SpriteList.push_back(new Object);

//if your compiler support unique_ptr, you could change auto_ptr to unique_ptr
//unique_ptr is a much more better choice than auto_ptr

like Scott Meyers said : "handle the resource by object"
Besides, according to exceptional c++ and more effective c++
if we don't handle the resource by object, it may bring us a lot of troubles

Edited by stereomatching

0
SpriteList.push_back(std::auto_ptr<Object>(new Object));

Sorry, I made a mistake

Edited by stereomatching

0

@Lerner: Actually, suhasgh's right. The delete kills the object instance, but the erase deletes the lingering pointer kept in memory. However, I'm curious about the erase statement and if it's killing the right entry each time.
As far as the for loop that cleans up, I'd yank the erase. Then after the for loop, I'd place a clear statement afterward. Clear will erase the entire list.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.