|
|
瘦瘦的柳树 · 苏州大学2005-2019复试上机真题及保研 ...· 1 年前 · |
|
|
气势凌人的大葱 · c++ - 'byte' : ...· 2 年前 · |
|
|
温文尔雅的钥匙 · CIM_LogicalDevice ...· 2 年前 · |
|
|
淡定的钥匙 · adb 关闭应用通知栏-掘金· 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;
|
|
气势凌人的大葱 · c++ - 'byte' : ambiguous symbol error when using of Crypto++ and Windows SDK - Stack Overflow 2 年前 |
|
|
淡定的钥匙 · adb 关闭应用通知栏-掘金 2 年前 |