Important: Please read the Qt Code of Conduct -

Dynamic allocation in QT: why "delete" operator in openglwindow example?

  • I'm new in QT and was trying to figure out how the dynamic allocation works. I was reviewing the OpenGL Window Example, and noticed that:

    1. One of the class members for OpenGLWindow class - m_device *QOpenGLPaintDevice is allocated dynamically; in the destructor the memory is freed by calling delete
    2. There is another class member QOpenGLContext *m_context which is allocated dynamically as well; yet it is not freed in the destructor.

    I was wondering if anyone could explain me why is it so? Why in this particular example QOpenGLPaintDevice is chosen to be destroyed and QOpenGLContext - not?

  • Lifetime Qt Champion

    hi , many items in Qt are inserted into
    containers or a parent and it will take ownership of the
    Like buttons you insert into a window. They will be deleted with the Window.
    so most likely the creation of the m_context assigns it to a parent and it will be deleted with that.
    m_context = new QOpenGLContext(this);
    this being the window.

  • Thank you for fast explanation! Makes much more sense now.

Log in to reply