考虑一个简单的计数过滤器:
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
最佳答案
sync
、strict_sync
和 flush
之间的主要区别在于它们的返回值。所有 3 个。它们都在属于满足 Flushable 的 filtering_stream
的任何过滤器或设备上调用 flush 方法概念。任何不支持可冲洗概念的过滤器/设备都会被简单地跳过。
sync
返回 true,除非可冲洗过滤器/设备之一返回 false。这意味着如果 filtering_stream
中有不可冲洗的过滤器/设备,数据可能会卡在其中,但 sync
会返回 true,因为它们不是可冲洗。
strict_sync
是类似的,除非它遇到一个非 Flushable Filter/Device。在这种情况下,strict_sync
将返回 false,即使所有可冲洗过滤器/设备都可能返回 true。这样做的原因是 strict_sync
的调用者知道如果它返回 true,则所有数据都已成功刷新。
成员 flush
简单地返回流的引用,有效地丢弃刷新是否成功。非成员(member) flush
has it's own rules for what it returns depending on the input value
在您的情况下,CountableOstreamFilter
不是 Flushable(它不能转换为必要的 flushable_tag)。因此,只要底层流上的刷新成功,对 sync
的调用将返回 true。但是,strict_sync
应该返回 false。
关于c++ - 在 boost iostream filtering_ostream 中,sync()、strict_sync() 和 flush() 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15143149/