我需要关闭一个std :: fstream? [英] do I need to close a std::fstream?

查看:254
本文介绍了我需要关闭一个std :: fstream?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能的重复:

是否需要手动关闭ifstream?

我需要调用 fstream.close()或者是 fstream 一个合适的RAII对象破坏流?

Do I need to call fstream.close() or is fstream a proper RAII object that closes the stream on destruction?

我在方法中有一个局部 std :: ofstream 对象。我可以假定该文件在退出此方法后总是关闭而不调用close?我找不到析构函数的文档。

I have a local std::ofstream object inside a method. Can I assume that the file is always closed after exiting this method without calling close? I could not find documentation of the destructor.

推荐答案

我认为以前的答案是误导。

I think the previous answers are misleading.

fstream 正确的RAII对象, 范围,并且当在范围结束时关闭时,手动地

fstream is a proper RAII object, it does close automatically at the end of the scope, and there is absolutely no need whatsoever to call close manually when closing at the end of the scope is sufficient.

特别是,它不是一个最佳实践,没有必要刷新输出。

In particular, it’s not a "best practice" and it’s not necessary to flush the output.

虽然Drakosha是正确的 close 让你可以检查流的失败位,没有人这样做。

And while Drakosha is right that calling close gives you the possibility to check the fail bit of the stream, nobody does that, anyway.

理想世界,我们会事先调用 stream.exception(ios :: failbit)并处理在 fstream 中抛出的异常$ c>的析构函数。但是不幸的是,析构函数中的异常在C ++中是一个破碎的概念,所以这不是一个好主意。

In an ideal world, one would simply call stream.exception(ios::failbit) beforehand and handle the exception that is thrown in an fstream’s destructor. But unfortunately exceptions in destructors are a broken concept in C++ so that’s not a good idea.

所以如果一个文件,手动(但只有这样)。

So if you want to check the success of closing a file, do it manually (but only then).

这篇关于我需要关闭一个std :: fstream?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆