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

你。 提交于 2019-12-23 12:26:01

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!