I'm exploring OpenGL with Qt6, and I came across some of their examples. The thing that draws my attention from a C++ perspective is the following piece of code.
delete m_program; // <-- is this necessary before creating m_program?
m_program = new QOpenGLShaderProgram;
m_program->addShaderFromSourceCode(QOpenGLShader::Vertex, vertexShaderSource);
m_program->addShaderFromSourceCode(QOpenGLShader::Fragment, fragmentShaderSource);
m_program->link();
// Create a VAO. Not strictly required for ES 3, but it is for plain OpenGL.
delete m_vao; // <-- is this necessary?
m_vao = new QOpenGLVertexArrayObject;
if (m_vao->create())
m_vao->bind();
m_program->bind();
delete m_vbo; // <-- is this necessary?
m_vbo = new QOpenGLBuffer;
m_vbo->create();
m_vbo->bind();
where
QOpenGLShaderProgram *m_program = nullptr;
QOpenGLBuffer *m_vbo = nullptr;
QOpenGLVertexArrayObject *m_vao = nullptr;
What is the point behind this practice? Why does one possibly need to delete nullptr before creating the object? Please note that in the code, these objects have not been created yet when the delete is called.
TL;DR:
The pointers are deleted because they might not be null in certain scenarios.
And if they are null in a specific scenario - deleteing them is OK because it does nothing.
More info:
If indeed the pointers are guaranteed to be null, then deleteing them before a new allocation is OK (delete with a null pointer does nothing - see e.g. here) but totally unnecessary.
But it seems like in this case the pointers are not guaranteed to be null.
For example this is done in GLWindow::initializeGL(), which might be called multiple times.
In the first time the pointers will be null, but in the next times they will not, and then it is a must to delete before reallocating them to avoid a memory leak.
Since as mentioned above deleteing a null pointer does nothing, the author of the code decided (correctly) it is not necessary to check for null.
Note that for example in the constructor GLWindow::GLWindow() pointers are not deleted before allocation because the author presumebaly understood there is no need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With