vector of pointers - deleting

closed account (zwA4jE8b)
Say I have

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class base
{
  virtual a();
  virtual b();
  virtual ~base(){std::cout << "~base" << std::endl;}
}

class derived:public base
{
  a();
  b();
  ~derived();
}

derived::~derived(){std::cout << "~derived" << std::endl;}


elsewhere I have

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
std::vector<base*> v_base;
std::vector<base*>::iterator it;

base* a = new derived;
v_base.push_back(a);

...more 'base*' pushed into vector

it = v_base.begin();
while(it != v_base.end())
{
  delete *it;
  it = v_base.erase(it);
}



should that not delete the dynamically allocated memory and then remove it from the vector?

When I test it i receive both destructor messages yet in my game, after I run the above code to clear out the vector, the objects are still there being drawn and updated.
Last edited on
closed account (zwA4jE8b)
I can post my game source code on mediafire if anyone cares to actually find the problem, lol
Yes show your real code, or more preferably a stripped down version that have the same problem.
Last edited on
closed account (zwA4jE8b)
http://www.mediafire.com/?qkaah71i3wd7e

Video Game design.zip has the source in Robo-venger -> src

gamengine.h/cpp is where the vector is declared. std::vector<game_object*> objs;
objects.h/cpp are the objects being stored in the vector

in gamengine the function remove_dead() seems to work fine.
I have it set up so that when playing if you hit 'p' the vector should be cleared out.
that function is re_init();

if you want to run the .exe all the needed dll's are in the dll.zip
(SDL and libgcc stuff)
Last edited on
1
2
else if(event.key.keysym.sym == SDLK_p)
	state = 'i';

Looks like init() is called when p is pressing.

You will also have to make sure that input() is not called between the calls to re_init() and init() because input() uses p1 that is a dangling pointer after re_init().

I also noticed an unrelated problem in hud.cpp. l_text and s_text are both created and freed inside hud::show and in the destructor you try to free them again.
Last edited on
closed account (zwA4jE8b)
wow, thanks. I was kind of thinking it was some bonehead error lol, like the wrong char.

Thanks a lot!

I guess I could take them out of the destructor. They are in the other function because for sdl_ttf fonts you have to free it before you can write to it again.
closed account (zwA4jE8b)
Again, thank you. That is such a relief!

this is my biggest project yet, so it is a little overwhelming
Last edited on
Topic archived. No new replies allowed.