I've spent most of the morning trying to figure this out and conceding defeat. I'm fairly new to C++, pointers, and the library, but not programming itself.
Quick Summary: I have a vector of pointers to class GameObject (a class i wrote). In a gameloop, I pass the vector by reference so each item in the vector can be rendered or have logic applied to it, etc. The problem is, the pointers in the vector seem to change arbitrarily after certain function calls (even when these function calls have nothing to do w/ the vector).
So far I'm using directx and some windows coding. I had objects up on screen, moving around, handling input, until I tried to get the location of the mouse cursor via GetCursorPos.
I'll try to just post relevant coding to demonstrate the problem and not drown it out with 100 pages of code.
Loop.cc - just create/allocate some pointers to GameObjects and add them to the vector. Then, loop and handle Input/Logic/Render
#include <vector>
#include "game.h"
#include "Global.h"
using namespace std;
INPUTDATA InputData;
// the main loop
void MainLoop() {
vector<GameObject*> gvec;
// paramaters in GameObject are stuff like xpos, ypos, width...
GameObject * g0 = new GameObject(200,300,64,64);
GameObject * g1 = new GameObject(100,400,64,64);
GameObject * g2 = new GameObject(400,400, 64, 64);
// add each pointer to the vector.
gvec.push_back(g0);
gvec.push_back(g1);
gvec.push_back(g2);
while (HandleMessages()) {
// get input data.
Input(&InputData);
// assertions added as quick way of verifying that the
// pointer in gvec is still equal to the original pointer.
// These three asserts don't fire (everything ok)....
assert(g0 == gvec[0]);
assert(g1 == gvec[1]);
assert(g2 == gvec[2]);
Logic(gvec, &InputData); // but somehow, in this function, the elements in the vector are altered.
assert(g0 == gvec[0]);
assert(g1 == gvec[1]);
assert(g2 == gvec[2]); // <-- this assertion reliably fires, address of gvec[2] changes???
Render(gvec);
}
}
Here is the details of Logic function in Logic.cc. It may not appear to do anything right now because I've deleted all the code that works ok, but the the below still makes it crash.
void Logic(std::vector<class GameObject*>& gvec, INPUTDATA* InputData) {
int x = 0;
int y = 0;
GetMouseXY(x, y); // If I comment this out or delete, everything works fine.
}
Here is the def of GetMouseXY in WinMain.cc. This is windows stuff and it blows my mind that the vector is effected at all.
bool GetMouseXY(int& x, int& y) {
LPPOINT p;
if(GetCursorPos(p)) {
x = p->x;
y = p->y;
return 1;
} else {
return 0;
}
}
So far, this has been enough to make me want to call the vector class buggy (which seems very silly) and just roll my own version. I'm sure its far more likely I've done something wrong or there is something I'm missing. Any ideas?