在boost iostream filtering_ostream中,sync(), strict_sync()和flu

in boost iostream filtering_ostream, what is the difference between sync(), strict_sync() and flush()?

本文关键字:sync strict flu boost iostream filtering ostream      更新时间:2023-10-16

考虑一个简单的计数过滤器:

class CountableOstreamFilter : public boost::iostreams::multichar_output_filter {
public:
    CountableOstreamFilter(): m_written(0) { 
    }
    template<typename Sink>
    std::streamsize write(Sink& dest, const char* s, std::streamsize n)
    {
            auto result  = boost::iostreams::write(dest, s, n);
            assert(n == result);
            m_written += result;
            return result;
    }
    inline std::streamsize writtenBytes() const {
        return m_written;
    }
private:
    std::streamsize m_written;
};

和这样使用

boost::iostreams::filtering_ostream counted_cout;
counted_cout.push(CountableOstreamFilter());
counted_cout.push(std::cout);
counted_cout << "hello world";

调用sync(), strict_sync()或flush()之间的区别是什么?counted_cout.sync ();//与这个调用有什么不同counted_cout.strict_sync ();//到这个调用counted_cout.flush ();//这个调用?

我使用boost 1.50.0

syncstrict_syncflush的关键区别在于它们的返回值。三个都是。它们都在任何过滤器或设备上调用flush方法,这些过滤器或设备是满足可冲洗概念的filtering_stream的一部分。任何不支持可冲洗概念的过滤器/设备都将被直接跳过。

sync返回true,除非其中一个可冲洗过滤器/设备返回false。这意味着,如果filtering_stream中有不可冲洗的过滤器/设备,则数据可能会卡在其中,但sync将返回true,因为它们不可冲洗。

strict_sync是类似的,除非它遇到不可冲洗的过滤器/设备。在这种情况下,strict_sync将返回false,即使所有可冲洗过滤器/设备可能返回true。这样做的原因是为了让strict_sync的调用者知道,如果它返回true,则表示所有数据都已成功刷新。

成员flush只是返回一个对流的引用,有效地丢弃了刷新是否成功。非成员flush根据输入值

有自己的返回规则。

在您的情况下,CountableOstreamFilter是不可冲洗的(它不能转换为必要的flushable_tag)。因此,只要底层流上的刷新成功,对sync的调用将返回true。但是,strict_sync应该返回false。