资源泄漏opengl/win32

Resource Leak opengl/win32

本文关键字:win32 opengl 泄漏 资源      更新时间:2023-10-16

你好,我最近开始学习win32/opengl,我设法写了一个在窗口内显示多色立方体的函数。我的问题是有一个资源泄漏,但我被难住了,不知道我到底忘记删除什么。

我已经把它缩小到这个函数

void display() 
{
    g.hglrc = wglCreateContext(g.hdc);
    wglMakeCurrent(g.hdc, g.hglrc);
    // make the color a white hue  
    glClearColor(1.0F, 1.0F, 1.0F, 1.0F);
    //  Clear screen and Z-buffer
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    // Reset transformations
    glLoadIdentity();
    // Rotate when user changes rotate_x and rotate_y
    glRotatef(rotate_x, 1.0, 0.0, 0.0);
    glRotatef(rotate_y, 0.0, 1.0, 0.0);
    //Multi-colored side - FRONT
    glBegin(GL_POLYGON);
    glColor3f(1.0, 0.0, 0.0);     glVertex3f(0.5, -0.5, -0.5);      // P1 is red
    glColor3f(0.0, 1.0, 0.0);     glVertex3f(0.5, 0.5, -0.5);      // P2 is green
    glColor3f(0.0, 0.0, 1.0);     glVertex3f(-0.5, 0.5, -0.5);      // P3 is blue
    glColor3f(1.0, 0.0, 1.0);     glVertex3f(-0.5, -0.5, -0.5);      // P4 is purple
    glEnd();
    // White side - BACK
    glBegin(GL_POLYGON);
    glColor3f(1.0, 1.0, 1.0);
    glVertex3f(0.5, -0.5, 0.5);
    glVertex3f(0.5, 0.5, 0.5);
    glVertex3f(-0.5, 0.5, 0.5);
    glVertex3f(-0.5, -0.5, 0.5);
    glEnd();
    // Purple side - RIGHT
    glBegin(GL_POLYGON);
    glColor3f(1.0, 0.0, 1.0);
    glVertex3f(0.5, -0.5, -0.5);
    glVertex3f(0.5, 0.5, -0.5);
    glVertex3f(0.5, 0.5, 0.5);
    glVertex3f(0.5, -0.5, 0.5);
    glEnd();
    // Green side - LEFT
    glBegin(GL_POLYGON);
    glColor3f(0.0, 1.0, 0.0);
    glVertex3f(-0.5, -0.5, 0.5);
    glVertex3f(-0.5, 0.5, 0.5);
    glVertex3f(-0.5, 0.5, -0.5);
    glVertex3f(-0.5, -0.5, -0.5);
    glEnd();
    // Blue side - TOP
    glBegin(GL_POLYGON);
    glColor3f(0.0, 0.0, 1.0);
    glVertex3f(0.5, 0.5, 0.5);
    glVertex3f(0.5, 0.5, -0.5);
    glVertex3f(-0.5, 0.5, -0.5);
    glVertex3f(-0.5, 0.5, 0.5);
    glEnd();
    // Red side - BOTTOM
    glBegin(GL_POLYGON);
    glColor3f(1.0, 0.0, 0.0);
    glVertex3f(0.5, -0.5, -0.5);
    glVertex3f(0.5, -0.5, 0.5);
    glVertex3f(-0.5, -0.5, 0.5);
    glVertex3f(-0.5, -0.5, -0.5);
    glEnd();
    wglMakeCurrent(NULL, NULL);
    SwapBuffers(g.hdc);
    ReleaseDC(g.hwnd, g.hdc);
    wglDeleteContext(g.hglrc);
}
g.hglrc = wglCreateContext(g.hdc);

别那样做。

您不需要在每次需要重新绘制屏幕时创建渲染上下文。你创建它一次;只有当你的窗口消失时,它才会消失。

现在,这并不一定证明为什么创建和销毁渲染上下文会留下资源。但这无关紧要;你不应该因为性能而这样做。呈现上下文的创建和销毁不是一个快速的过程,也不打算如此。