如何在分配到ostream后关闭stream? [英] How to close ofstream after assigning to ostream?
本文介绍了如何在分配到ostream后关闭stream?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以做
std::ostream& out = condition ? std::cout : std::ofstream(filename);
但是如果 out = std :: ofstream文件名)
?
推荐答案
我理解你想要使用 out
?
您不需要明确地关闭它。 std :: fstream
是RAII对象,因此它将在封闭范围结束时自动关闭打开的文件。
You don't need to close it explicitly. std::fstream
is RAII object, so it will close an opened file automatically at the end of enclosing scope.
当然,如果你真的需要关闭文件,你总是可以 out
:
And of course, you can always cast out
if you really need to close the file just now:
if( ptr = dynamic_cast<std::ofstream*>(out) ) {
ptr->close();
}
这篇关于如何在分配到ostream后关闭stream?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文