Skip to main content
GameDev.net gamedev.net
🔒 Locked

Program crashes and vectors

Started by LewisDe Aug 6, 2013 at 6:34 PM 0 replies 1.2k views
Original Post
LewisDe
LewisDe
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.
SyncViews
SyncViews

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 ©)" 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 >" 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
    //You could also consider other solutions since right now your loading an
    //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];
    }
}

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.