问题描述
当我使用 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的用途,让析构函数做它的工作。手动关闭它是没有坏处的,但它不是C ++的方式,它在C中用类进行编程。
如果要在结束之前关闭文件
在标准(27.8.1.5类模板basic_ifstream)中, ifstream 要用保存实际文件句柄的 basic_filebuf 成员来实现。它作为一个成员持有,以便当一个ifstream对象销毁时,它也调用 basic_filebuf 上的析构函数。从标准(27.8.1.2),析构函数关闭文件:
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:
这篇关于我需要手动关闭ifstream吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!