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


i'm getting segmentation faults (i think) current method of vector.push_back().

here example code:

so have class zombie

class zombie {     public:        zombie();        ~zombie();         sdl_surface* image;         sdl_rect box;         bool dead;     protected:     private:        // gets random coordinates around screen        sdl_rect get_zombie_rect();  }; 

with constructor being:

zombie::zombie()    :    dead(false),    image(load_image("player.png")),    box(get_zombie_rect()) {  } 

and zombie has handler class manage vector function called create_new_zombie(). (here problem)

void zombie_manager::create_new_zombie() {    zombie newzombie;    zombies.push_back(newzombie); } 

is correct way add element vector?

i'm able working version use of pointers, there has easier , more correct way of accomplishing this, right?

why getting seg fault if std::vector.push_back() shallow copies new elements? wrong in assuming that?

you need implement copy constructor , assignment operator.

zombies.push_back(newzombie); pushes copy of newzombie in vector. when method enters, original newzombie destroyed. , i'm willing bet in ~zombie() call delete image;.

because don't have proper copy constructor , assignment operator, copies invalid, because contain dangling pointer.

always follow rule of three - if need implement destructor, need implement c-ctor , assignment operator.


Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -