问题
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) ?
回答1:
Yes, it is closed automatically (Qt documentation), so there is no need to call close().
回答2:
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.
来源:https://stackoverflow.com/questions/12931436/do-i-really-need-to-call-qfileclose-in-this-case