gpt4 book ai didi

c++ - 如果我不关闭,ifstream 会导致内存泄漏吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:44:52 26 4
gpt4 key购买 nike

我已经研究了下面的问题,我知道我不必关闭 ifstream 因为文件处理程序在退出范围时会自动关闭。 [肯定没有内存泄漏][ Do I need to manually close an ifstream? 1

但在下面的代码中,文件处理程序是一个全局变量。所以如果我们不手动关闭文件处理程序,我认为它会导致内存泄漏。该假设是否正确,或者文件处理程序将由 C++ 自动处理?

#include <iostream>
#include <fstream>
#include <sstream>
#include <unistd.h>

using namespace::std;

ifstream config_file;
stringstream cmd;

int test() {
config_file.open("config.file");
cmd << config_file.rdbuf();
string tmp = cmd.str();
cout << " config buffer is " << tmp << "\n" <<endl;
}

int main () {
test();
while (1) {
test();
sleep(1);
}
}

有趣的是,cppcheck 也没有报告此文件中的内存泄漏。

cppcheck file.cpp 
//no error logs.

有人可以确认上面的代码中是否存在内存泄漏吗?

最佳答案

没有。 fstream 是一个 RAII对象,它会在作用域结束时自动关闭。这意味着它最终以任何方式为您关闭。

但是,您可以通过显式调用 close 手动关闭它,或者使用大括号 {} 简单地将它嵌套在范围内。

另一种情况出现,如果你想检查文件关闭是否成功。比你还必须手动调用它。如果您想保证代码中的某个点是完整写入文件的,这将很有用。

另请务必查看 cppreference了解更多信息。

linux man-page for close陈述如下,读起来也很有趣

Not checking the return value of close() is a common but nevertheless serious programming error. It is quite possible that errors on a previous write(2) operation are first reported at the final close(). Not checking the return value when closing the file may lead to silent loss of data. This can especially be observed with NFS and with disk quota.

A successful close does not guarantee that the data has been successfully saved to disk, as the kernel defers writes. It is not common for a filesystem to flush the buffers when the stream is closed. If you need to be sure that the data is physically stored use fsync(2). (It will depend on the disk hardware at this point.)

It is probably unwise to close file descriptors while they may be in use by system calls in other threads in the same process. Since a file descriptor may be reused, there are some obscure race conditions that may cause unintended side effects.

windows上flush的情况不太清楚。也许有人可以添加此信息。

进一步 close() 保证在失败时抛出一个您可以捕获和处理的异常。

关于c++ - 如果我不关闭,ifstream 会导致内存泄漏吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52061145/

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