<ca********@gmail.com> wrote in message
news:11**********************@o13g2000cwo.googlegr oups.com
I have a class Scene that has several subclasses: World, Vault, etc.
I fill a vector with these classes and then cannot go through and
delete them. What's the trick to deleting pointers from a vector?
Code:
std::vector<Scene*> scenes;
void initializeGame()
{
robot = new Robot("COM2");
player = new Player();
//Add Scenes
scenes.push_back(new World(robot, player));
scenes.push_back(new SecurityWires(robot));
scenes.push_back(new Keypad(robot));
scenes.push_back(new Maze(robot, player));
scenes.push_back(new Explosives(robot, player));
scenes.push_back(new Vault(robot));
scenes.push_back(new Map());
}
void endGame()
{
for(int i = 0; i < scenes.size(); i++)
{
delete scenes[i];
}
scenes.clear();
}
When my program starts, I call intializeGame. When I go to exit the
game, I call endGame() and I get an assertion failure. Any ideas?
What is the assertion that fails?
There is no trick to deleting pointers from a vector. For example, the
following runs without any problems. The fact that your code doesn't run
correctly suggests that the problem is in code that you haven't shown us.
Where do robot and player come from, for example, and when are they
destructed? What is the destructor code for your derived classes?
In the example below, I have given Base a virtual destructor. This makes no
difference in my example, but is necessary in general if you want the
derived class destructors to be called.
#include <vector>
class Base
{
public:
virtual ~Base()
{}
};
class Derived1 : public Base
{
};
class Derived2 : public Base
{
};
int main()
{
std::vector<Base *> v;
v.push_back(new Derived1);
v.push_back(new Derived2);
for (size_t i=0; i<v.size(); ++i)
delete v[i];
v.clear();
return 0;
}
--
John Carson