[Qt-interest] QFile private member

andrew.m.goth at l-3com.com andrew.m.goth at l-3com.com
Wed Feb 11 00:18:35 CET 2009


Bob Hood wrote:
> Scott Aron Bloom wrote:
> > Simply making it a QFile *, and then in the constructor, creating a
> > blank QFile...
> 
> Remembering, of course, to delete it in your destructor

QFile is derived from QObject, so you should use Qt's object ownership
mechanism.  When you create the QFile, pass a parent (owning) object
pointer to its constructor.  That parent object's QObject destructor
will automatically delete the QFile for you.

Of course, this assumes there *is* a parent QObject to point to, which
won't be the case if you are putting this QFile* in a class that is not
derived from QObject or one of its subclasses.  In this situation, you
will have to manually delete the QFile* when you're done with it.

Class definition:

MyClass: public QObject {
Q_OBJECT
public:
    MyClass(QObject* parent = 0);
protected:
    QFile* file;
};

Constructor (approach #1):

MyClass::MyClass(QObject* parent):
    QObject(parent),
    file(new QFile(this))
{}

Constructor (approach #2):

MyClass::MyClass(QObject* parent):
    QObject(parent)
{
    file = new QFile(this);
}

You can also pass a filename to QFile's constructor.

-- 
Andy Goth
<amgoth at link.com>




More information about the Qt-interest-old mailing list