Important: Please read the Qt Code of Conduct -

Delete or not?[RESOLVED]

  • Hi
    I am unsure as to when I need to use delete
    given this code
    namespace Reporting
    class ReportElementWriter: public QObject



    ReportElementWriter(const QString& filename,QObject* parent = 0);
    virtual ~ReportElementWriter();
    bool write(const QTextDocument* document);

    QIODevice m_QIODevice;
    QuaZip *m_zipArchive;
    QBuffer m_contentBuffer;

    In the corresponding implentation file I allocate the member variables
    m_QIODevice(new QFile(filename)

    Do I need to delete them in my destructor?

  • Yes, you do, if you use this way of creating a new QFile object.

    QObjects and subclasses there of (that includes QFile) all have constructors that optionally take a parent object. If you use that constructor to set a parent, that parent becomes responsible for the life time of the object you created. If you don't use it, it is your responsibility to otherwise make sure you delete the object instance when you're done with it.

  • Hi thanks for clarifying that for me
    So if I create the QFile object like this
    m_QIODevice(new QFile(filename,parent)
    I would not need to delete m_QIODevice?


  • That's correct. You still could, but if not, the parent object will delete it (m_QIODevice) when it (the parent) gets deleted.

  • Thanks

Log in to reply