1919
2020#include <iostream>
2121#include <sstream>
22+ #include <stdexcept>
2223#include <string>
2324
24- // NOLINTNEXTLINE(readability-redundant-declaration) - TODO: fix this
25- extern std::ostringstream errout;
26- // NOLINTNEXTLINE(readability-redundant-declaration) - TODO: fix this
27- extern std::ostringstream output;
2825/**
2926 * @brief Utility class for capturing cout and cerr to ostringstream buffers
3027 * for later use. Uses RAII to stop redirection when the object goes out of
@@ -47,34 +44,35 @@ class RedirectOutputError {
4744 }
4845
4946 /** Revert cout and cerr behaviour */
50- ~RedirectOutputError() {
47+ ~RedirectOutputError() noexcept(false) {
5148 std::cout.rdbuf(_oldCout); // restore cout's original streambuf
5249 std::cerr.rdbuf(_oldCerr); // restore cerrs's original streambuf
5350
54- errout << _err.str();
55- output << _out.str();
51+ {
52+ const std::string s = _out.str();
53+ if (!s.empty())
54+ throw std::runtime_error("unconsumed stdout: " + s); // cppcheck-suppress exceptThrowInDestructor - FP #11031
55+ }
56+
57+ {
58+ const std::string s = _err.str();
59+ if (!s.empty())
60+ throw std::runtime_error("consumed stderr: " + s);
61+ }
5662 }
5763
58- /** Return what would be printed to cout. See also clearOutput() */
59- std::string getOutput() const {
60- return _out.str();
61- }
62-
63- /** Normally called after getOutput() to prevent same text to be returned
64- twice. */
65- void clearOutput() {
64+ /** Return what would be printed to cout. */
65+ std::string getOutput() {
66+ std::string s = _out.str();
6667 _out.str("");
68+ return s;
6769 }
6870
69- /** Return what would be printed to cerr. See also clearErrout() */
70- std::string getErrout() const {
71- return _err.str();
72- }
73-
74- /** Normally called after getErrout() to prevent same text to be returned
75- twice. */
76- void clearErrout() {
71+ /** Return what would be printed to cerr. */
72+ std::string getErrout() {
73+ std::string s = _err.str();
7774 _err.str("");
75+ return s;
7876 }
7977
8078private:
@@ -112,9 +110,7 @@ class SuppressOutput {
112110
113111#define REDIRECT RedirectOutputError redir
114112#define GET_REDIRECT_OUTPUT redir.getOutput()
115- #define CLEAR_REDIRECT_OUTPUT redir.clearOutput()
116113#define GET_REDIRECT_ERROUT redir.getErrout()
117- #define CLEAR_REDIRECT_ERROUT redir.clearErrout()
118114
119115#define SUPPRESS SuppressOutput supprout
120116
0 commit comments