daisy
daisy

Reputation: 23501

Do I really need to call QFile::close() in this case?

I'm not sure about QFile's behavior,

bool Class::Function (const QString & name)
{
  QFile fp (name);
  if (fp.open (QIODevice::ReadOnly))
  {
     // read file
     return false;
  }
  return true;
}

Hmm, it's not like a FILE* pointer in C (which you must close and free), would this be a problem if I don't call QFile::close() (Does it do automatically on destruction) ?

Upvotes: 9

Views: 8459

Answers (2)

user362638
user362638

Reputation:

QFile object is closed automatically (Qt documentation) upon its destructor; hence there is no need to call close() explicitly.

Upvotes: 16

jonathanzh
jonathanzh

Reputation: 1454

I prefer calling fp.close() before the function returns: This may not be necessary but may not be harmful either.

The Qt documentation may not reflect the actual code. For example, following is the source code in Qt 5.5.0:

/*!
    Destroys the file object, closing it if necessary.
*/
QFile::~QFile()
{
}

So QFile::close() is not automatically called in the destructor. The documentation may need to be updated.

As an added advantage, Matching QFile::open() with QFile::close() will ensure that the file can be properly opened again the next time function bool Class::Function() is called.

Upvotes: -1

Related Questions