@@ -236,6 +236,45 @@ namespace xcpp
236236 return " unknown" ;
237237 }
238238
239+ class SilentStreamRedirectRAII
240+ {
241+ public:
242+
243+ explicit SilentStreamRedirectRAII (bool silent)
244+ : m_silent(silent)
245+ , m_old_cout(silent ? std::cout.rdbuf() : nullptr)
246+ , m_old_cerr(silent ? std::cerr.rdbuf() : nullptr)
247+ {
248+ if (m_silent)
249+ {
250+ std::cout.rdbuf (&m_null);
251+ std::cerr.rdbuf (&m_null);
252+ }
253+ }
254+
255+ ~SilentStreamRedirectRAII () noexcept
256+ {
257+ if (m_silent)
258+ {
259+ std::cout.rdbuf (m_old_cout);
260+ std::cerr.rdbuf (m_old_cerr);
261+ }
262+ }
263+
264+ SilentStreamRedirectRAII (const SilentStreamRedirectRAII&) = delete ;
265+ SilentStreamRedirectRAII& operator =(const SilentStreamRedirectRAII&) = delete ;
266+ SilentStreamRedirectRAII (SilentStreamRedirectRAII&&) = delete ;
267+ SilentStreamRedirectRAII& operator =(SilentStreamRedirectRAII&&) = delete ;
268+
269+ private:
270+
271+ bool m_silent;
272+ xnull m_null;
273+
274+ std::streambuf* m_old_cout;
275+ std::streambuf* m_old_cerr;
276+ };
277+
239278 interpreter::interpreter (int argc, const char * const * argv) :
240279 xmagics ()
241280 , p_cout_strbuf(nullptr )
@@ -288,16 +327,7 @@ namespace xcpp
288327
289328 // If silent is set to true, temporarily dismiss all std::cerr and
290329 // std::cout outputs resulting from `process_code`.
291-
292- auto cout_strbuf = std::cout.rdbuf ();
293- auto cerr_strbuf = std::cerr.rdbuf ();
294-
295- if (config.silent )
296- {
297- auto null = xnull ();
298- std::cout.rdbuf (&null);
299- std::cerr.rdbuf (&null);
300- }
330+ SilentStreamRedirectRAII silent_guard (config.silent );
301331
302332 std::string err;
303333
@@ -331,13 +361,6 @@ namespace xcpp
331361 std::cout << std::flush;
332362 std::cerr << std::flush;
333363
334- // Reset non-silent output buffers
335- if (config.silent )
336- {
337- std::cout.rdbuf (cout_strbuf);
338- std::cerr.rdbuf (cerr_strbuf);
339- }
340-
341364 // Depending of error level, publish execution result or execution
342365 // error, and compose execute_reply message.
343366 if (errorlevel)
0 commit comments