I’ve a method in a class that get’s a pointer to another object (of a different class)and adds an object (of another different class) to a vector that is a member variable of the first object (the one that is passed as a parameter). This is the code:
ObstacleManager::ObstacleManager(Application *lApp)
{
app=lApp;
GLfloat obstacleVerts[12]={
-0.1f,-0.2f,0.0f,
0.1f,-0.2f,0.0f,
-0.1f,0.2f,0.0f,
0.1f,0.2f,0.0f
};
StandardObstacle obstacle(obstacleVerts,-0.7f,0.0f,4);
obstacle.manager=this;
lApp->characters.push_back(&obstacle);
}
I think the problem is that the obstacle object gets released when it shouldn’t, because if I change the code and create the obstacle with a “new” (if you create an object with new you have to manually delete it, don’t you?) It works. Like this:
ObstacleManager::ObstacleManager(Application *lApp)
{
app=lApp;
GLfloat obstacleVerts[12]={
-0.1f,-0.2f,0.0f,
0.1f,-0.2f,0.0f,
-0.1f,0.2f,0.0f,
0.1f,0.2f,0.0f
};
StandardObstacle *obstacle=new StandardObstacle(obstacleVerts,-0.7f,0.0f,4);
obstacle->manager=this;
lApp->characters.push_back(obstacle);
}
Is there a way to prevent this from happening?
You are passing the address of a local object to the vector, the local object does not exist once the constructor returns and your vector then has a pointer which points to invalidated memory.
You will have to make the object persist, possible ways are:
Just push the object by value or
Use dynamically allocated object but instead of raw pointer use a smart pointer like
shared_ptras the vector element type.