Search code examples
c++visual-c++-2010

Issue with Pointers (Only in Release Build)


unsure how to go about describing this but here i go:

For some reason, when trying to create a release build version of my game to test, the enemy creation aspect of it isn't working.

Enemies *e_level1[3];
e_level1[0] = &Enemies(sdlLib, 500, 2, 3, 128, -250, 32, 32, 0, 1);
e_level1[1] = &Enemies(sdlLib, 500, 2, 3, 128, -325, 32, 32, 3, 1);
e_level1[2] = &Enemies(sdlLib, 500, 2, 3, 128, -550, 32, 32, 1, 1);

Thats how i'm creating my enemies. Works fine when in the debug configuration but when i switch to the release config, it doesn't seem to initialize the enemies correctly.

To me, this seems a bit strange that it works in debug but not in release, any help appreciated on what mostly is what i've done wrong.


Solution

  • Other people have already pointed out the error, namely that the temporaries are getting destroyed straight away, but all of the answers so far are using manual memory management - it's more idiomatic in C++ to use e.g. std::vector for something like this, e.g.

    std::vector<Enemies> enemies;
    enemies.push_back(Enemies(sdlLib, 500, 2, 3, 128, -250, 32, 32, 0, 1));
    enemies.push_back(Enemies(sdlLib, 500, 2, 3, 128, -325, 32, 32, 3, 1));
    enemies.push_back(Enemies(sdlLib, 500, 2, 3, 128, -550, 32, 32, 1, 1));
    

    Then you just access the Enemies instances as enemies[0] through enemies[2] and they get cleaned up automatically when the vector goes out of scope.