Having trouble adding more than 2 objects to a vector

-1

I'm working on a Parallax scrolling project, in which I need to get multiple sprites up on the screen at once. To do this, and to make the code remotely reusable, I am using some vectors to hold my ParallaxSegment objects.

ParallaxSegment* seg;
vector<ParallaxSegment> parsega;

These are created as private members in my main Game class. Later on, in the Game's constructor, I have this:

Game::Game() : Scene("Game"),
    m_Logo(nullptr),
    seg(nullptr),
    m_Timer(0.0f)
{
    seg = new ParallaxSegment("Leaves1@2x", 1334);
    parsega.push_back(*seg);

    seg = new ParallaxSegment("Leaves2@2x", 1334);
    parsega.push_back(*seg);

    seg = new ParallaxSegment("Leaves3@2x", 1334);
    parsega.push_back(*seg);

    seg = new ParallaxSegment("Leaves4@2x", 1334);
    parsega.push_back(*seg);
}

The ParallaxSegments seem to be created just fine, and push_back works for the first two uses. However, upon using it a third time, I get the following error:

Unhandled exception at 0x003EED82 in GameDev2D.exe: 0xC0000005: Access violation reading location 0x0000001C.

and am redirected to the deconstructor for Sprite, which ParallaxSegment inherits from:

Sprite::~Sprite()
{
    //Set the shader to null
    m_Shader = nullptr;

    //Cycle through and delete all the frames in the sprite
    for(unsigned int i = 0; i < m_Frames.size(); i++)
    {
        delete m_Frames.at(i); //This line, specifically, is where the program terminates
        m_Frames.at(i) = nullptr;
    }

    m_Frames.clear();
}

I tried using just Sprites instead of my slightly modified ParallaxSegment class, but the problem still exists, and I'm brought back to the same place. Am I doing something wrong with the push_back function? Am I creating the new Sprites wrong? Should I be deleting them before making a new one?

c++
vector
asked on Stack Overflow Feb 24, 2015 by Alfabit

1 Answer

0
vector<ParallaxSegment> parsega;
[...]
ParallaxSegment* seg = new ParallaxSegment(...);
parsega.push_back(*seg);

Your vector doesn't hold pointers to ParallaxSegments but 'real' ParallaxSegment objects. Thus you create a pointer to a ParallaxSegment object, dereference it to store the object in the vector. This is 'too complicated'.

But remember: Your vector holds objects, not pointers. Thus you cannot call 'delete m_Frames.at(i)', because you try to delete an object instead of a pointer. That's when the Access Violation happens.

answered on Stack Overflow Feb 24, 2015 by Sorin Totuarez

User contributions licensed under CC BY-SA 3.0