【问题标题】:in boost iostream filtering_ostream, what is the difference between sync(), strict_sync() and flush()?在 boost iostream filtering_ostream 中,sync()、strict_sync() 和 flush() 有什么区别?
【发布时间】:2013-02-15 02:14:28
【问题描述】:

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

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

【问题讨论】:

    标签: c++ boost iostream boost-iostreams


    【解决方案1】:

    syncstrict_syncflush 之间的主要区别在于它们的返回值。他们三个。它们都在满足Flushable 概念的filtering_stream 的一部分的任何过滤器或设备上调用flush 方法。任何不支持 Flushable 概念的过滤器/设备都会被跳过。

    sync 返回真,除非可冲洗过滤器/设备之一返回假。这意味着如果 filtering_stream 中存在不可刷新的过滤器/设备,数据可能会卡在其中,但 sync 将返回 true,因为它们不是可刷新的。

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

    成员flush 简单地返回对流的引用,有效地丢弃无论刷新是否成功。非会员flushhas it's own rules for what it returns depending on the input value

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

    【讨论】:

      猜你喜欢
      • 2012-12-24
      • 1970-01-01
      • 2015-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多