Re: Deleteing Objects from std::vector

From: John Carson (jcarson_n_o_sp_am__at_netspace.net.au)
Date: 03/14/05


Date: Mon, 14 Mar 2005 19:42:18 +1100


<canned.net@gmail.com> wrote in message
news:1110786437.599384.179130@o13g2000cwo.googlegroups.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 


Relevant Pages

  • Re: Polymorphism
    ... then also making derived classes destructors virtual ... So I am thinking that if the Base class destructor is not made virtual ... class X: public Base {public: virtual void Print() ...
    (alt.comp.lang.learn.c-cpp)
  • Re: Would a static_cast be better style here?
    ... "Steven T. Hatton" wrote in message ... class derived1: public base ... > int main ...
    (comp.lang.cpp)
  • Re: BUG: compiler allows for creation of objects without destructor compiled
    ... But it is an error to actually call the destructor of that ... Yes and no. Comeau online ... seems to have it bugs in this area, which are different than VC's bugs. ... class derived: public base; ...
    (microsoft.public.dotnet.languages.vc)