Followers 0

# Program crashes and vectors

## 1 post in this topic

Hey guys, I need your help. I'm creating a simple space game with SDL and I hold a vector of projectiles. Whenever I attempt to push_back() a new element, the game suddenly ends. Please forgive any n00b mistakes as I'm learning the ropes of C++. The code is posted here: http://pastebin.com/7NAv82Aa and the SpawnProjectile() function is located on line 243.
0

##### Share on other sites

If you are going to pass Projectiles around by value with those fields, you need to implement a copy operator (https://en.wikipedia.org/wiki/Rule_of_three_%28C%2B%2B_programming%29) "Projectile& operator = (Projectile &copy)" as a member function. The default copy operator will not copy your pointer fields correctly, leaving them pointing to the original Projectile, and if that gets deleted, invalidates the pointers.

I cant remember the exact cases for std::vector to use copy construction or the copy operator, but examples would be push_back, insert, erase and resize.

It might be a better idea to use a vector of pointers, e.g. "std::vector<std::unique_ptr<Projectile> >" to avoid these copies completely.

Also your copy constructor could be a lot more simple, e.g. just copy things

Projectile::Projectile(const Projectile& proj)
{
this->x = proj.x;
this->y = proj.y;
this->xVel = proj.xVel;
this->damage = proj.damage;
this->frame = proj.frame;
this->type = proj.type;
this->direction = proj.direction;
//You need to assign it to something, not sure what you want
this->personalID = proj.personalID;
this->maxFrame = proj.maxFrame;
//You need to add a copyImage
//image multiple times into memory by the looks of things
this->sprite = copyImage(proj.sprite);

//This is not technically exception safe. Somthing like another std::vector
//or at least std::unique_ptr would be better than raw pointers here
animLeft = new SDL_Rect[maxFrame];
animRight = new SDL_Rect[maxFrame];
//Copy animation
for (int i = 0; i < maxFrame; ++i)
{
animLeft[i] = proj.animLeft[i];
animRight[i] = proj.animRight[i];
}
}

1

## Create an account

Register a new account