简体   繁体   English

重写的std :: ostream flush()函数未被std :: flush调用

[英]Overridden std::ostream flush() function not called by std::flush

I've overridden std::ostream::flush() function. 我已经覆盖了std::ostream::flush()函数。 Below I've removed all other code from the example: 下面我从示例中删除了所有其他代码:

#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
        }

};

I try to use it like this: 我试着像这样使用它:

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

, but the overridden CMyStream::flush() or CMyStream::sync() functions are not called by the std::flush manipulator. ,但是重写的CMyStream::flush()CMyStream::sync()函数不会被std::flush操作CMyStream::sync()调用。 If I debug I see that the default std::ostream::flush() is called and not my overriden function. 如果我调试我看到默认的std::ostream::flush()被调用而不是我的覆盖函数。

Is there a way around this problem, or do I have to call myStream.flush() directly and not with the manipulator? 有没有解决这个问题的方法,或者我是否必须直接调用myStream.flush()而不是操纵器?

The problem is that std::ostream::flush method is not virtual, so you cannot properly override it, and you should not. 问题是std::ostream::flush方法不是虚拟的,所以你不能正确覆盖它,你不应该。 What you should do instead is to create your own buffer class inherited from std::basic_streambuf or std::basic_filebuf or std::basic_stringbuf and override protected int sync() method in there. 你应该做的是创建自己的缓冲类,继承自std::basic_streambufstd::basic_filebufstd::basic_stringbuf并在那里覆盖protected int sync()方法。 Your stream class then should create proper buffer type in it's constructor. 然后你的流类应该在它的构造函数中创建适当的缓冲区类型。

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

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