Virtual functions and vectors

Started by
12 comments, last by Aardvajk 15 years, 4 months ago
Kind of the same. But (to the OP) watch out for this:

void f(){    Bird b;    Wombat w;    some_non_local_vector.push_back(&b);    some_non_local_vector.push_back(&w);}// function exits, b and w are destroyed but vector still contains pointers,// which now point to garbage memory

Advertisement
Yes, i was confronted with that problem a while ago
I didn't have a clue how to fix it for like half an hour :D
But i found it eventually...

void SetupEngine()
{
phWorld.AddBody(new CphBall(Vector2f(300.0f,300.0f),300.0f));
}

This is how it works now, i don't have to define a global 'CphBall', i just use 'new' :p
(this code is from the so called 'physics engine' i try to make)
Personally I would change your code to the following which uses boost's shared pointer and returns references to constant Animals. The reason for the constant references is to do away with some of the pointer syntax and not to allow code to change the animal.
#include <iostream>#include <vector>#include <boost/shared_ptr.hpp>class Animal;typedef boost::shared_ptr<Animal> Animal_ptr;class Animal{  public:  virtual void WhatAmI()const{std::cout<<"i am an animal!"<<std::endl;};      };            class Bird : public Animal{      public:      void WhatAmI()const{std::cout<<"i am a bird!"<<std::endl;};   };                          class World{private:  std::vector<Animal_ptr> Animals;public:  void AddAnimal(Animal_ptr a) { Animals.push_back(a); }  Animal const& GetAnimal(int const& index)const {return *Animals[index];}};  int main(){    World w;    w.AddAnimal( Animal_ptr(new Bird) );    w.AddAnimal( Animal_ptr(new Animal) );    w.GetAnimal(0).WhatAmI();    w.GetAnimal(1).WhatAmI();}

Quote:Original post by Martijnvdc
Yes, i was confronted with that problem a while ago
I didn't have a clue how to fix it for like half an hour :D
But i found it eventually...

void SetupEngine()
{
phWorld.AddBody(new CphBall(Vector2f(300.0f,300.0f),300.0f));
}

This is how it works now, i don't have to define a global 'CphBall', i just use 'new' :p
(this code is from the so called 'physics engine' i try to make)


Just remember that since you new-ed it, it is your responsibility to delete it. This is (urgh, urgh) not really necessary if it is only created once and and needs to be deleted at program termination (urgh, urgh) as your OS will almost certainly reclaim memory used by your program at termination, but if you are allocating in a loop, or whatever, you'll end up leaking memory.

But forget that and delete what you new. Or use a container or smart pointer, as mentioned above, that takes ownership of the pointers and deletes them when the container goes out of scope.

This topic is closed to new replies.

Advertisement