Jump to content
  • Advertisement
Sign in to follow this  

Program crashes and vectors

This topic is 1904 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post

Link to post
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
    //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];

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!