gpt4 book ai didi

c++ - 我需要手动关闭 ifstream 吗?

转载 作者:IT老高 更新时间:2023-10-28 11:28:41 31 4
gpt4 key购买 nike

使用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关闭文件?

最佳答案

没有

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

如果你想在函数结束之前关闭文件,你总是可以使用嵌套范围。

在标准(27.8.1.5 类模板 basic_ifstream)中,ifstream将使用 basic_filebuf 来实现持有实际文件句柄的成员。它作为一个成员保存,因此当 ifstream 对象析构时,它还会在 basic_filebuf 上调用析构函数。 .从标准 (27.8.1.2) 来看,该析构函数会关闭文件:

virtual ˜basic_filebuf();

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

关于c++ - 我需要手动关闭 ifstream 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/748014/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com