Jump to content

  • Log In with Google      Sign In   
  • Create Account

Program crashes and vectors


Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.


  • You cannot reply to this topic
1 reply to this topic

#1   Members   -  Reputation: 105

Like
0Likes
Like

Posted 06 August 2013 - 12:34 PM

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.

#2   Members   -  Reputation: 712

Like
1Likes
Like

Posted 06 August 2013 - 12:51 PM

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
    //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];
    }
}





Old topic!

Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.




PARTNERS