c++ - 为什么需要销毁使用 boost::iostreams::zlib_compressor 的 boost::iostream::filtering_ostream 才能写入接收器?
问题描述
今天花了一些时间调试问题后,我注意到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
.
大肠杆菌的结果: https ://coliru.stacked-crooked.com/a/7cd166d2d820e838
这种行为背后的原因是什么?
解决方案
这实际上与这个问题有关:
刷新 boost::iostreams::zlib_compressor。如何获得“同步刷新”?
你需要一个调用来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();
}
推荐阅读
- c - 如何通过使用 FEM(语言:C)中的元素连通性来查找非零项的数量?
- facebook - 作为页面发布到 Facebook 群组
- google-cloud-platform - googleapi:错误 403:资源上的权限“cloudfunctions.functions.create”被拒绝
- python - 假设每一行都有这两个值,如何获取列的两个值的百分比
- python-3.x - Python 嵌套 for 循环而不是 itertools
- python - 列表索引超出范围 - 如何解决这个问题?
- javascript - 如何在 jquery 或 javascript 中的某个变量下从 firebase 接收数据
- python - sympy 解决函数给出错误的结果
- c# - 从 CryptoStream 读取文件内容而不写入文件
- asynchronous - 使用 async/await 生锈 lazy_static?