c++ - std::flush 未调用重写的 std::ostreamlush() 函数

标签 c++ templates stl flush ostream

我已经重写了 std::ostream::flush() 函数。下面我从示例中删除了所有其他代码:

#include <iostream>
#include <ostream>

class CMyStream : public std::streambuf, public std::ostream
{
    public:
        explicit CMyStream() throw() : std::ostream(this)
        {
            // Intentionally empty block
        }

        std::ostream &flush() 
        { 
            std::cout << "Overridden flush called\n"; 
            return (*this);
        }

        int sync()
        {
            std::cout << "Overridden sync called\n";
            return 0;   // Success
        }

};

我尝试这样使用它:

CMyStream myStream;
myStream << "Test" << std::flush;

,但覆盖的 CMyStream::flush()CMyStream::sync() 函数不会由 std::flush 调用> 机械手。如果我调试,我会看到默认的 std::ostream::flush() 被调用,而不是我的重写函数。

有办法解决这个问题,还是我必须直接调用 myStream.flush() 而不是使用操纵器?

最佳答案

问题是 std::ostream::flush 方法不是虚拟的,所以你不能正确地重写它,你也不应该这样做。相反,您应该做的是创建自己的缓冲区类,继承自 std::basic_streambufstd::basic_filebufstd::basic_stringbuf 并且重写其中 protected intsync() 方法。然后,您的流类应该在其构造函数中创建正确的缓冲区类型。

关于c++ - std::flush 未调用重写的 std::ostreamlush() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25019067/

相关文章:

javascript - 在露天 freemarkuer 模板中列出 javascript 数组

c++ - 基于模板类型重构c++模板类

c++ - std::string_view 和 std::string in std::unordered_set

c++ - 是否需要 std::any_of 遵循短路逻辑?

c++ - 使用 C++ 动态分配/dev/ttyUSB*

c++ - 在 dll 中使用 std::list 无法解析的外部符号

c++ - 从有符号到无符号问题的类型转换

c++ - c++中使用unordered_map实现哈希表并处理冲突

c++ - 尝试包装函数返回值时出现 "<class name> does not provide a call operator"错误

c++ - 跨平台可重复数字生成器