Bryce Howard
Bryce Howard

Reputation: 58

proper use of std::vector.push_back() with a user defined type

I'm getting segmentation faults (I think) with my current method of vector.push_back().

Here is some example code:

So I have my class Zombie

class Zombie
{
    public:
       Zombie();
       ~Zombie();

       SDL_Surface* image;

       SDL_Rect box;

       bool dead;

   protected:

   private:
       // gets random coordinates around the screen
       SDL_Rect get_zombie_rect();
 };

with the constructor being:

Zombie::Zombie()
   :
   dead(false),
   image(load_image("Player.png")),
   box(get_zombie_rect())
{

}

and Zombie has a handler class to manage the vector with a function called create_new_zombie(). (here is the problem)

void Zombie_Manager::create_new_zombie()
{
   Zombie newZombie;
   zombies.push_back(newZombie);
}

Is this the correct way to add an element to a vector?

I'm able to get a working version with the use of pointers, but there has to be an easier and more correct way of accomplishing this, right?

Why am I getting a seg fault if std::vector.push_back() shallow copies its new elements? Am I wrong in assuming that?

Upvotes: 3

Views: 2179

Answers (1)

Luchian Grigore
Luchian Grigore

Reputation: 258648

You need to implement a copy constructor and an assignment operator.

zombies.push_back(newZombie); pushes a copy of newZombie in the vector. When the method enters, the original newZombie is destroyed. And I'm willing to bet that in ~Zombie() you call delete image;.

Because you don't have a proper copy constructor and assignment operator, all copies will be invalid, because they will contain dangling pointer.

Always follow the rule of three - if you need to implement a destructor, you also need to implement a c-ctor and assignment operator.

Upvotes: 9

Related Questions