我需要手动关闭ifstream吗? [英] Do I need to manually close an ifstream?

查看:2266
本文介绍了我需要手动关闭ifstream吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用 std :: ifstream ?时,我需要手动调用 close()吗? >

例如,在代码中:

  std :: string readContentsOfFile :: string fileName){

std :: ifstream file(fileName.c_str());

if(file.good()){
std :: stringstream buffer;
buffer<< file.rdbuf();
file.close();

return buffer.str();
}
throw std :: runtime_exception(file not found);
}



我需要调用 file.close 手动?不应 ifstream 使用 RAII 关闭文件?

解决方案



这是RAII的用途,让析构函数做它的工作。手动关闭它是没有坏处的,但它不是C ++的方式,它在C中用类进行编程。



如果要在结束之前关闭文件



在标准(27.8.1.5类模板basic_ifstream)中, ifstream 要用保存实际文件句柄的 basic_filebuf 成员来实现。它作为一个成员持有,以便当一个ifstream对象销毁时,它也调用 basic_filebuf 上的析构函数。从标准(27.8.1.2),析构函数关闭文件:


virtual ~basic_filebuf c



效果:销毁类 basic_filebuf< charT,traits& code>。调用 close()



Do I need to manually call close() when I use a std::ifstream?

For example, in the code:

std::string readContentsOfFile(std::string fileName) {

  std::ifstream file(fileName.c_str());

  if (file.good()) {
      std::stringstream buffer;
      buffer << file.rdbuf();
      file.close();

      return buffer.str();
  }
  throw std::runtime_exception("file not found");
}

Do I need to call file.close() manually? Shouldn't ifstream make use of RAII for closing files?

解决方案

NO

This is what RAII is for, let the destructor do its job. There is no harm in closing it manually, but it's not the C++ way, it's programming in C with classes.

If you want to close the file before the end of a function you can always use a nested scope.

In the standard (27.8.1.5 Class template basic_ifstream), ifstream is to be implemented with a basic_filebuf member holding the actual file handle. It is held as a member so that when an ifstream object destructs, it also calls the destructor on basic_filebuf. And from the standard (27.8.1.2), that destructor closes the file:

virtual ˜basic_filebuf();

Effects: Destroys an object of class basic_filebuf<charT,traits>. Calls close().

这篇关于我需要手动关闭ifstream吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆