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

标签 c++ linux file memory-management memory-leaks

我已经研究了下面的问题,我知道我不必关闭 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/

相关文章:

c++ - 如果emplace_back完全错误,为什么QTCreator不警告我?

ubuntu 上的 Java 内存不足,但存在大量缓存内存

java - 如何使用java将文件夹从一个位置移动到另一个位置

c++ - 设计文件夹/文件系统?

c++ - Windows 中用于生物特征身份验证的凭据提供程序

c++ - 从 C++ 应用程序将 List 和 numpy.matrix 传递给 python 函数

Linux 命令 reset(1) 很慢

c# - Azure 函数在 Linux 上出现 'Listener unable to start' 错误

c - 如何修复 .txt 中的 &localtime - C

c - 同时访问文件。奇怪的锁定行为