I have a ostream-based subclass which captures debug messages of my program.
/** @brief Customized output stream with "tee" feature */
template <typename CharT, typename Traits = std::char_traits<CharT> >
class basic_tostream : public std::basic_ostream<CharT, Traits> {
public:
basic_tostream(std::basic_ostream<CharT, Traits> & o1, /**< main ostream */
std::basic_ostream<CharT, Traits> & o2 /**< teed ostream */)
: std::basic_ostream<CharT, Traits>(&tbuf), tbuf(o1.rdbuf(), o2.rdbuf())
{ /* empty */ }
private:
tee_outbuf<CharT, Traits> tbuf;
}; // end_class: basic_tostream
How I use this class:
std::ofstream debugFile("debug.txt")
tostream tout(std::cout, debugFile);
/* computation */
tout << "message\n";
/* other computation */
Issue: The class work fine when the application exits normally. But in case of crashing (e.g. array index out of bound, etc), the 'tout' did print out all message to console, but the 'debugFile' does not capture all the printout.
Question: So, how to properly flush the ostream buffer to output file in case when the application crash?
One way is to use a crash handler. In windows, this is in the form of dbghlp.dll
and the just-in-time debugging subsystem.
But by far the easiest way is to flush on every message in one of two ways:
flush
after every message.I believe that using endl
instead of "\n"
will implicitly flush.