|
|
耍酷的草稿本 · 西安交通大学辩论队喜夺“华夏杯”国际华语辩论 ...· 1 年前 · |
|
|
失落的伤疤 · 六一儿童白雪公主七个小矮人演出服成人话剧王子 ...· 2 年前 · |
|
|
呐喊的白开水 · 魍魉之花-魍魉之花在线漫画-在线漫画-腾讯动 ...· 2 年前 · |
|
|
强悍的核桃 · 抢先试驾一汽丰田bZ3,比亚迪“代工”的丰田 ...· 2 年前 · |
使用
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;