簡體   English   中英

使用boost :: iostreams :: zlib_compressor為什么需要銷毀boost :: iostream :: filtering_ostream才能寫入接收器?

[英]Why boost::iostream::filtering_ostream using boost::iostreams::zlib_compressor needs to be destroyed for the sink to be written?

在花了很長時間調試今天的問題之后,我注意到需要銷毀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()不能解決問題,當我刪除zlib_compressor時我zlib_compressor

結果與coliru: https ://coliru.stacked-crooked.com/a/7cd166d2d820e838

這種行為背后的原因是什么?

這實際上與這個問題有關:

刷新boost :: iostreams :: zlib_compressor。 如何獲得“同步刷新”?

你需要調用boost::iostreams::zlib_compressor::close來進行刷新。

你可以通過在boost::iostream::filtering_ostream上調用pop()reset()來實現這一點。

注意, 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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM