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

Mar*_*nix 11 c++ opengl glut console-application 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; 
    } 
}
Run Code Online (Sandbox Code Playgroud)

那么正确的是:

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

出了什么问题是:

  1. 使用CTRL + C关闭控制台应用程序,它从上面给出了异常.

这是在Visual Studio 2008 C++中.

UPDATE

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

atexit() 似乎工作得很好,所以也许我可以使用它?

Maa*_*ten 13

我用这个函数:

void glutLeaveMainLoop ( void ); 
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

  • 好的,根据最新的GLUT规范(3.7),`glutLeaveMainLoop()`不再存在了.那么现在OP问题的答案是什么? (5认同)
  • Ubuntu 有它,但有一个技巧。Ubuntu 上的 GLUT 都是 FreeGLUT,FreeGLUT 分为 _std 和 _ext 头文件。如果包含`GL/glut.h`,它只包含`freeglut_std.h`。您必须包含“GL/freeglut.h”,其中包括 _std 和“freeglut_ext.h”标头,然后您会得到“glutLeaveMainLoop()”。 (3认同)

小智 5

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

glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE,GLUT_ACTION_CONTINUE_EXECUTION);
Run Code Online (Sandbox Code Playgroud)

无论何时你想离开mainloop而不使用termiante应用程序使用:

glutLeaveMainLoop();
Run Code Online (Sandbox Code Playgroud)

不要忘记包含"freeglut.h"