C++正确的清理重定向缓冲区

C++ proper cleanup redirected buffer for tee ostream

本文关键字:重定向 缓冲区 C++      更新时间:2023-10-16

我需要将消息输出到控制台和日志文件。在谷歌搜索之后,我学会了"teebuf"概念,它基本上创建了一个从basic_streambuf继承的自定义类。这工作正常,但如何正确清理重定向的缓冲区。我的意思是如何为"tee"缓冲区实现 RAII,这样我就不需要每次需要退出程序时都打扰它。

备注:目前使用提升库对我来说不是一个选择。

代码段

int main() {
    std::streambuf* cout_sbuf = std::cout.rdbuf();
    std::ofstream   fout(fileOutDebug);
    teeoutbuf       teeout(std::cout.rdbuf(), fout.rdbuf());
    std::cout.rdbuf(&teeout);
    // some code ...
    if (failed) {
        std::cout.rdbuf(cout_sbuf); // <-- i once comment this and it gives error
        return -1;
    }
    // some more code ...
    std::cout.rdbuf(cout_sbuf); // <-- i once comment this and it gives error
    return 0;
}

代码段(我的试用版实现,但失败)

template < typename CharT, typename Traits = std::char_traits<CharT>
> class basic_tostream : std::basic_ostream<CharT, Traits>
{
    public:
        basic_tostream(std::basic_ostream<CharT, Traits> & o1,
                       std::basic_ostream<CharT, Traits> & o2)
    : std::basic_ostream<CharT, Traits>(&tbuf), 
      tbuf(o1.rdbuf(), o2.rdbuf()) {}
        void print(char* msg);
    private:
    basic_teebuf<CharT, Traits> tbuf; // internal buffer (tee-version)
};
typedef basic_tostream<char> tostream;
int main() {
    std::ofstream fout(fileOutDebug);
    tostream tee(std::cout, fout, verbose);
    tee << "test 1n"; // <-- compile error
    tee.print("sometext"); // <-- comment above and it run fine, both file and console written
}

错误消息:"std::basic_ostream"是无法访问的"basic_tostream"基础

你应该使用:

template < typename CharT, typename Traits = std::char_traits<CharT> >
class basic_tostream : public std::basic_ostream<CharT, Traits>

而不是:

template < typename CharT, typename Traits = std::char_traits<CharT> >
class basic_tostream : std::basic_ostream<CharT, Traits>

关键区别在于public。这就是'std::basic_ostream' is an inaccessible base of 'basic_tostream'错误消息的内容。