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...

Recommended Answers

All 4 Replies

Why the call to erase()?

Everything else looks okay to me on first run through.

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

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

Sorry, I made a mistake

@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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.