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

StackOverflow https://stackoverflow.com/questions/15143149

Question

considering a simple counting filter:

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

and using it thus:

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

what would be the difference between calling sync(), strict_sync() or flush()? counted_cout.sync(); // what is different from this call counted_cout.strict_sync(); // to this call counted_cout.flush(); // to this call?

I'm using boost 1.50.0

Was it helpful?

Solution

The key difference between sync, strict_sync, and flush is their return values. All 3 of them . All of them call the flush method on any Filter or Device that's part of the filtering_stream that satisfies the Flushable concept. Any Filter/Device that does not support the Flushable concept is simply skipped.

sync returns true unless one of the Flushable Filters/Devices returns false. This means that if there are non-Flushable Filters/Devices that are part of the filtering_stream, data could get stuck in them, but sync would return true, since they are not Flushable.

strict_sync is similar, except if it encounters a non-Flushable Filter/Device. In this case, strict_sync will return false, even though all of the Flushable Filters/Devices might return true. The reason for this is so that a caller of strict_sync knows that if it returns true, all of the data was successfully flushed.

The member flush simply returns a reference to the stream,effectively discarding whether or not the flush was successful. The non-member flush has it's own rules for what it returns depending on the input value

In your case, the CountableOstreamFilter is not Flushable (it's not convertible to the necessary flushable_tag). Hence, calls to sync will return true as long as the flush on the underlying stream is successful. However, strict_sync should return false.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top