关闭FreeGLUT最好的方法是什么?

时间:2011-02-17 19:51:11

标签: c++ opengl console-application glut freeglut

我在使用FreeGLUT关闭我的控制台应用程序时遇到了麻烦。

我想知道最好的方法是采取一切可能的结果,因为我不希望任何内存泄漏(我非常害怕那些)。

所以我已经尝试了以下内容,这给了我一个例外:

  

myProject.exe中0x754e6a6f的第一次机会异常:0x40010005:Control-C。

int main(int argc, char **argv)
{
    if( SetConsoleCtrlHandler( (PHANDLER_ROUTINE) CtrlHandler, true) )
    {
        // more code here as well ....


        glutCloseFunc(close); // set the window closing function of opengl
        glutMainLoop();
        close(); // close function if coming here somehow
    }
    else
    {
        return 1;
    }
    return 0;
}

void close()
{
    // keyboardManager is a pointer to a class
    // which I want to delete, so no memory will leak.
    if(keyboardManager) // do I need this check?
        delete keyboardManager;
}

bool CtrlHandler(DWORD fdwCtrlType)
{
    switch(fdwCtrlType)
    {
        // Handle the CTRL-C signal.
        case CTRL_C_EVENT:
        // and the close button
        case CTRL_CLOSE_EVENT:
          close();
          return true;

        // Pass other signals to the next handler. 
        case CTRL_BREAK_EVENT:
            return false;

    // delete the pointer anyway
        case CTRL_LOGOFF_EVENT:
        case CTRL_SHUTDOWN_EVENT:
        default:
            close();
            return false; 
    } 
}

所以正确的是:

  1. 关闭过剩的窗口
  2. 使用x
  3. 关闭控制台应用程序
  4. 使用我的键盘管理员if(keyboardManager->isKeyDown[27]) glutExit();
  5. 关闭我的过剩窗口

    出了什么问题:

    1. 使用CTRL + C关闭控制台应用程序,它从上面提供例外。
    2. 这是在Visual Studio 2008 C ++中。

      更新

      我发现异常被抛出,因为我正在调试。所以那不是问题。但问题仍然存在:实际关闭过剩的最优雅方式是什么?

      atexit()似乎也有效,所以也许我可以使用它?

4 个答案:

答案 0 :(得分:13)

我使用这个功能:

void glutLeaveMainLoop ( void ); 

有关sourceforge页面的更多信息,但我从未使用过该功能:

  

glutLeaveMainLoop函数导致freeglut停止事件循环。如果GLUT_ACTION_ON_WINDOW_CLOSE选项已设置为GLUT_ACTION_CONTINUE_EXECUTION,则控制将返回到名为glutMainLoop的函数;否则申请将退出。

http://freeglut.sourceforge.net/docs/api.php#EventProcessing

在空指针上使用delete是安全的,无需检查。

答案 1 :(得分:5)

感谢Maarten的帖子,这对我有用:

glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE,GLUT_ACTION_CONTINUE_EXECUTION);

每当你想要使用应用程序时不使用termiante的主循环:

glutLeaveMainLoop();
不要忘记包含" freeglut.h"

答案 2 :(得分:1)

我使用glutDestroyWindow(int handle);

根据ID:OpenGL论坛上的RigidBody

void destroy_window() 
{
 window_valid = -1;
}

void display_func() 
{
 if(window_valid == -1)
   return;
 // draw things
}

答案 3 :(得分:0)

尝试此方法:

glutDestroyWindow(glutGetWindow());
相关问题