How to close ofstream after assigning to ostream?
问题 I can do std::ostream& out = condition ? std::cout : std::ofstream(filename); but how do I close in case of out = std::ofstream(filename) ? 回答1: As I understood you want to close file stream using out ? 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. 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(); }