带有文件名的 std::ifstream 初始化

Aru*_*run 5 c++ ifstream

我正在使用以下代码来检查文件是否存在或不使用std::ifstream.

#include <iostream>
#include <fstream>

int main()
{
    if (std::ifstream("file.txt"))
    {
        std::cout << "File present\n";
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

由于我没有使用任何对象std::ifstream,我该如何关闭文件?还是不需要调用close?

Ser*_*gey 4

实际上,您正在使用 的未命名临时对象std::ifstream。不需要调用std::ifstream::close(),因为对象在使用后被销毁,并且它的析构函数正确关闭文件。

更准确地说:

// Temporary object is not yet created here
if (std::ifstream("file.txt"))
{
    // Temporary object is already destroyed here
    std::cout << "File present\n";
}
// Or here
Run Code Online (Sandbox Code Playgroud)

来自文档

(析构函数)[虚拟](隐式声明)

破坏 basic_ifstream 和关联的缓冲区,关闭文件