简体   繁体   中英

Tracing calls to std::cout

How does one trace calls to std::cout?

The situation I run into every now and then is code (usually some 3rd party code) that will make a call to std::cout and the buffer is not immediately flushed.

Thus the data will is not printed to stdout immediately and shows up later when something else has called std::cout and flushed the buffer via std::endl or std::flush. I am thus left wondering who called std::cout? Now I have to chase it down C++ standard library function call. If the call to std::cout is deeply buried, it can be an annoyance to track down.

What are good ways to trace std::cout or any similar C++ standard library function to see where it is being called? My platform is Linux, though this could apply to any system.

The easiest approach is to cause std::cout to always flush:

std::cout << std::unitbuf;

Assuming std::cout is used it will get automatically flushed by all properly written output operations (eg, all output operations provided by the standard C++ library are properly written).

To actually track these operations down in a debugger the easiest approach is using a non-buffering filtering stream buffer: as there is no buffer this stream buffer's overflow() method is called for each character which is then easy to intercept in a debugger:

struct trackbuf
    : std::streambuf {
    std::ostream&.   d_out;
    std::streambuf* d_sbuf;
    explicit trackbuf(std::ostream& out)
        : d_out(out), d_sbuf(out.rdbuf(this)) {
    }
    ~trackbuf() { this->d_out.rdbuf(this->d_sbuf); }
    int overflow(int c) override {
        return this->d_sbuf->sputc(c); // set breakpoint here
    }
};

// ...
int main() {
    trackbuf buf(std::cout);
    // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM