![]() |
听话的香菜 · location.href和push的区别 ...· 9 月前 · |
![]() |
私奔的硬盘 · 前端过滤,搜索框注入案例 - ...· 10 月前 · |
![]() |
干练的火柴 · 已经有了各省的数据,如何将信息以可视化的方式 ...· 1 年前 · |
![]() |
失恋的滑板 · JS中对URL进行转码与解码_51CTO博客 ...· 1 年前 · |
使用
std::ifstream
时是否需要手动调用
close()
例如,在代码中:
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");
}
是否需要手动调用
file.close()
?
ifstream
不应该使用
RAII
来关闭文件吗?
不,这是由
ifstream
析构函数自动完成的。您应该手动调用它的唯一原因是因为
fstream
实例的作用域很大,例如,如果它是一个长期存在的类实例的成员变量。
我同意@Martin的说法。如果您写入文件,数据可能仍然位于缓冲区中,并且可能在调用
close()
之前不会写入文件。如果不手动执行此操作,您就不知道是否存在错误。不向用户报告错误是一种非常糟糕的做法。
你可以让析构函数来做它的工作。但就像任何RAII对象一样,有时手动调用close可能会有所不同。例如:
#include <fstream>
using std::ofstream;
int main() {
ofstream ofs("hello.txt");
ofs << "Hello world\n";
return 0;
}
写入文件内容。但是:
#include <stdlib.h>
#include <fstream>
using std::ofstream;
![]() |
私奔的硬盘 · 前端过滤,搜索框注入案例 - blacksunny - 博客园 10 月前 |