开发者

delete dynamically allocated memory in openGL

I use C++ and and freeglut, and want to know how to delete the dynamically allocated memory using new. I need to free the memory when closing the window. Where should I put this delete pointer? before glutMainLoop()?

*Update*.

For example, I use int *ptr = new int[n] to store the vertex coordinates, and did not use class in the code. So I have to call delete in the main() to开发者_Python百科 free the memory. I understand that I can use vector to do the same thing. But in my case, if I have to use new, how can I deallocate the memory?


The old form of GLUT made it so that your program's execution never returned from the call to glutMainLoop. FreeGLUT gets rid of this, but only if you specifically ask for it before calling glutMainLoop:

glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_CONTINUE_EXECUTION);

This means that, when you eventually call glutLeaveMainLoop, FreeGLUT will continue from where glutMainLoop was called, just like a regular function call.

So if you allocate memory before glutMainLoop, you can delete that memory afterwards.

That being said:

I use int *ptr = new int[n] to store the vertex coordinates

Why isn't that a std::vector<int> mem(n); instead of a pointer? You can still get a pointer to the memory by doing &mem[0]. And it will clean up after itself.


See question 3.0.70 in the OpenGL GLUT FAQ. Short answer is use an exit handler installed via the atexit() call.


Use smart pointers and you won't need to worry about it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜