[英]How to delete a C++ object being drawn by OpenGL?
I have a list(vector) of objects, which are continuously being drawn on screen. 我有一个对象列表(矢量),这些对象不断在屏幕上绘制。 During the glutMainLoop, I have this glutTimerFunction update, which periodically checks if an object goes out of the screen boundaries, and if it is so, it deletes the object. 在glutMainLoop期间,我进行了glutTimerFunction更新,该更新会定期检查对象是否超出屏幕边界,如果是,则删除该对象。 This is giving a segmentation fault. 这给出了分段错误。
Here is the class -> 这是课程->
class bullet
{
private:
public:
void update();
bool check()
{
if(y>=box_len/2)
{
return true;
}
return false;
}
void draw();
};
vector <bullet*> bullets;
Here is the update function -> 这是更新功能->
void update(int value)
{
for( typeof(bullets.begin()) it= bullets.begin(); it!= bullets.end();it++)
{
if((*it)!=NULL)
{
if(*it)->check())
{
delete *it;
bullets.erase(it);
}
}
}
glutTimerFunc(10, update, 0);
}
Registerd with glut in main() as 在glut中将main()注册为
glutTimerFunc(10, update, 0);
I'm guessing tr
is some sort of foreach macro? 我猜tr
是某种foreach宏吗?
In which case, removing an item from your vector
will invalidate the iterator. 在这种情况下,从vector
删除一项将使迭代器无效。
Use it = bullets.erase(it);
使用it = bullets.erase(it);
to ensure your iterator stays valid. 以确保您的迭代器保持有效。
When the element being deleted is the last element, the iterator becomes the next element ( bullets.end() in this case). 当要删除的元素是最后一个元素时,迭代器将成为下一个元素(在本例中为bullets.end())。 The increment at the end of the for loop, causes it to become something invalid and was the reason for the segfault. for循环末尾的增量导致它变得无效,这是段错误的原因。
Repaired code -> 修复的代码->
void update(int value)
{
for( typeof(bullets.begin()) it= bullets.begin(); it!= bullets.end();it++)
{
if((*it)!=NULL)
{
if(*it)->check())
{
delete *it;
bullets.erase(it);
if(it==bullets.end())
break;
}
}
}
glutTimerFunc(10, update, 0);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.