简体   繁体   English

跟踪对std :: cout的调用

[英]Tracing calls to std::cout

How does one trace calls to std::cout? 如何跟踪对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. 我时不时遇到的情况是代码(通常是一些第三方代码),该代码将调用std :: cout且缓冲区不会立即刷新。

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. 因此,数据不会立即打印到stdout,而是在其他调用std :: cout并通过std :: endl或std :: flush刷新缓冲区时显示。 I am thus left wondering who called std::cout? 因此,我想知道谁叫std :: cout? Now I have to chase it down C++ standard library function call. 现在,我必须逐一介绍C ++标准库函数调用。 If the call to std::cout is deeply buried, it can be an annoyance to track down. 如果对std :: cout的调用根深蒂固,那么跟踪下去可能会很烦人。

What are good ways to trace std::cout or any similar C++ standard library function to see where it is being called? 有什么好的方法可以跟踪std :: cout或任何类似的C ++标准库函数以查看在何处调用它? My platform is Linux, though this could apply to any system. 我的平台是Linux,尽管它可以应用于任何系统。

The easiest approach is to cause std::cout to always flush: 最简单的方法是使std::cout始终刷新:

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). 假设使用了std::cout ,它将被所有正确编写的输出操作自动刷新(例如,标准C ++库提供的所有输出操作都被正确编写)。

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: 要在调试器中实际跟踪这些操作,最简单的方法是使用非缓冲过滤流缓冲区:由于没有缓冲区,因此会为每个字符调用此流缓冲区的overflow()方法,从而易于在调试器中进行拦截:

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);
    // ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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