Help with delete and vector

If you are a new Irrlicht Engine user, and have a newbie-question, this is the forum for you. You may also post general programming questions here.
Post Reply
geckoman
Posts: 143
Joined: Thu Nov 27, 2008 11:05 am
Location: Germany
Contact:

Help with delete and vector

Post by geckoman »

I have a vector<someclass*> as private member of a class a.
If I delete class a, do I have to do nothing or do I have to delete the vector or even loop through the vector and delete them?

Code: Select all

class a
{
public:
a()
{
vec = new vector<someclass*>();
};
~a()
{
//what to do here?
}
private:
vector<someclass*> *vec;
};
Even though I know C++ quite good, sometimes I better ask someone ^^
hybrid
Admin
Posts: 14143
Joined: Wed Apr 19, 2006 9:20 pm
Location: Oldenburg(Oldb), Germany
Contact:

Post by hybrid »

every new must be backed by a delete. So you need to call delete on your vector. Thogh it would be even better to make the vector a real member of the class, not just a pointer. That way you wouldn't need the new, and hence also no delete.
geckoman
Posts: 143
Joined: Thu Nov 27, 2008 11:05 am
Location: Germany
Contact:

Post by geckoman »

Ok thanks, but that means, I have to delete every pointer in the vector one by one (loop) before deleting the vector, don't I?
Sylence
Posts: 725
Joined: Sat Mar 03, 2007 9:01 pm
Location: Germany
Contact:

Post by Sylence »

Yes.

Code: Select all

for( u32 i=0; i<vector.size(); ++i)
   delete vector[i];
simple as that
Software documentation is like sex. If it's good you want more. If it's bad it's better than nothing.
hybrid
Admin
Posts: 14143
Joined: Wed Apr 19, 2006 9:20 pm
Location: Oldenburg(Oldb), Germany
Contact:

Post by hybrid »

Not necessarily. That depends on how you create the objects you point to.
geckoman
Posts: 143
Joined: Thu Nov 27, 2008 11:05 am
Location: Germany
Contact:

Post by geckoman »

I create them outside the class and add them to the vector via a method in the class like so:

Code: Select all

addToVec(someclass *pSomeclass);
hybrid
Admin
Posts: 14143
Joined: Wed Apr 19, 2006 9:20 pm
Location: Oldenburg(Oldb), Germany
Contact:

Post by hybrid »

Well, there's even more to this. It depends on a) if you create them with 'new' as well, and b) if this vector is the only place they are referenced from. In case any of the answers is no then you must not call delete. Otherwise you should. At least if I didn't forget any other condition...
Post Reply