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.
deletewith a null pointer does nothing, so it's OK, but totally unnecessary. See e.g. here. Maybe the code is written like that because there are cases where the pointers are not null (and then it's a must todeletethem to avoid a memory leak).deleteis called --- this is a wrong assumption for a public member function.inititializeGL()is a public member that can be called at any time during the object's life.nullptrin the class body.