为什么需要破坏使用boost :: iostreams :: zlib_compressor的boost :: iostream :: filtering_ostream才能写入接收器?

时间:2019-03-21 20:10:40

标签: c++ boost iostream

今天花了很多时间调试问题之后,我注意到template <typename base> class derived { template<size_t size> void do_stuff() { (...) } void do_stuff(size_t size) { (...) } public: void execute() { if constexpr(is_constexpr(base::get_data()) { do_stuff<base::get_data()>(); } else { do_stuff(base::get_data()); } } } 需要销毁才能写入接收器。

测试代码:

boost::iostream::filtering_ostream

致电#include <boost/iostreams/filtering_stream.hpp> #include <boost/iostreams/filter/zlib.hpp> #include <sstream> struct ZlibOstream : boost::iostreams::filtering_ostream { ZlibOstream(std::ostream& os) { boost::iostreams::filtering_ostream::push(boost::iostreams::zlib_compressor{}); boost::iostreams::filtering_ostream::push(os); } }; int main() { std::ostringstream oss; #ifdef HAS_SCOPE { #endif ZlibOstream zlibOstream{oss}; zlibOstream << "This is a test string.\n"; #ifdef HAS_SCOPE } #endif return (oss.tellp() == 0); } 并不能解决问题,删除flush()时也不需要这样做。

大肠杆菌的结果:https://coliru.stacked-crooked.com/a/7cd166d2d820e838

此行为背后的原因是什么?

1 个答案:

答案 0 :(得分:0)

这实际上与以下问题有关:

Flushing a boost::iostreams::zlib_compressor. How to obtain a "sync flush"?

您需要调用boost::iostreams::zlib_compressor::close才能进行刷新。

您可以通过在pop()上调用reset()boost::iostream::filtering_ostream来实现。

请注意,pop()的名称建议弹出链中的最后一个过滤器,而reset()则要完全清除链,以使filtering_ostream之后无法使用。

示例:

#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/filter/zlib.hpp>

#include <sstream>

struct ZlibOstream : boost::iostreams::filtering_ostream
{
    ZlibOstream(std::ostream& os)
    {
        boost::iostreams::filtering_ostream::push(boost::iostreams::zlib_compressor{});
        boost::iostreams::filtering_ostream::push(os);
    }
};

int main()
{   
    std::ostringstream oss;

    ZlibOstream zlibOstream{oss};

    zlibOstream << "This is a test string.\n";

    zlibOstream.reset(); // needed if you want to write to oss

    return oss.tellp();
}