|
Prev: considerations regarding active issue #711 (contradiction in empty shared_ptr)
Next: std::terminate() and std::unexpected()
From: Rune Allnor on 16 Jun 2008 08:27 Hi all. Section 13.10.3 of the Josuttis book on the STL contains a basic recipe on how to redirect output written to std::cout to some other stream. However, the section contains a cautionary remark that std::cout should be restored to its initial state before program termination. Is there a standard way to handle this safely? Some sort of RAII pattern where the constructor redirects std::cout to some destination and the destructor resets whatever was modified? Rune -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ]
From: Amal Pillai on 17 Jun 2008 04:44 > Is there a standard way to handle this safely? Some sort of > RAII pattern where the constructor redirects std::cout to some > destination and the destructor resets whatever was modified? Well, does not your question contain the answer ? A simple wrapper class like the one below (redirector) should work fine. Please note that the implementation is not thread-safe nor does it check for errors. -Amal // simplistic implementation, you might want to check the ofstream and // throw exceptions and so on class redirector { std::streambuf* cout_buf_; std::streambuf* cerr_buf_; public: redirector(std::ofstream& ofs) : cout_buf_(0), cerr_buf_(0) { cout_buf_ = std::cout.rdbuf(ofs.rdbuf()); cerr_buf_ = std::cerr.rdbuf(ofs.rdbuf()); } ~redirector() { std::cout.rdbuf(cout_buf_); std::cerr.rdbuf(cerr_buf_); } }; -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ]
From: Ulrich Eckhardt on 17 Jun 2008 04:47
Rune Allnor wrote: > Section 13.10.3 of the Josuttis book on the STL contains a > basic recipe on how to redirect output written to std::cout > to some other stream. However, the section contains a > cautionary remark that std::cout should be restored to its > initial state before program termination. > > Is there a standard way to handle this safely? Some sort of > RAII pattern where the constructor redirects std::cout to some > destination and the destructor resets whatever was modified? Sure, using RAII works for this. I believe that Boost also contains a 'state saver' utility class for IOStreams, which helps with this or actually does this. Uli -- Sator Laser GmbH Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932 [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ] |