openglbuffer-objects

Should VBO be unbound before calling glDeleteBuffers?


Is it required that we should unbind a buffer object before deleting it? If I had bound it in a VAO and deleted it without unbinding (binding to 0), what will happen? Will the reference still exist?

public void dispose()
{
    glBindVertexArray(0);
    glDeleteVertexArrays(vaoID);

    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glDeleteBuffers(vboVertID);
    glDeleteBuffers(vboColID);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
    glDeleteBuffers(eboID);
}

Is it a good or a bad practice to unbind before deletion?


Solution

  • Is it necessary?

      No.

    Is it a good idea?

      Possibly, but not in your current pseudo-code.


    The only time you would want to manually unbind a resource in GL prior to deletion is if you have it bound in a separate context. That is because one the criteria for actually freeing the memory associated with a GL resource is that it have a reference count of 0. glDelete* (...) only unbinds an object from the current context prior to putting it on a queue of objects to free.

    If you delete it while a VAO that is not currently bound holds a pointer to this buffer, or if it is bound in a completely different OpenGL context from the one you call glDelete* (...) in, then the reference count does not reach 0 before glDelete* (...) finishes. As a result, the memory will not be freed until you actually unbind it from or destroy all VAO / render contexts that are holding references. You will effectively leak memory until you take care of all the dangling references.

    In short, glDelete* (...) will always unbind resources from the current context and reclaim any names for immediate reuse, but it will only free the associated memory if after unbinding it the reference count is 0.


    In this case, unbinding is completely unnecessary because you are doing so in the same context you call glDeleteBuffers (...) from. This call implicitly unbinds the object you are deleting, so you are doing something redundant. What is more, you already deleted your VAO prior to calling glDeleteBuffers (...) -- when that VAO was deleted, it relinquished all of its pointers and thus decremented the reference count to your buffer.