boost asio streambuf don't release memory after calling consume?

心不动则不痛 提交于 2019-12-01 05:04:36

问题


boost::asio::streambuf b;
...
void handler(const boost::system::error_code& e, std::size_t size)
{
  if (!e)
  {
    std::stringstream sstr(std::string((std::istreambuf_iterator<char>(&b)), 
        std::istreambuf_iterator<char>()));
    b.consume(size);
    ...
  }
}
...
boost::asio::async_read_until(s, b, "END\r\n", handler);

when the consume method is called, the memory occupied by streambuf b is not released. The memory will grow up as async_read_until is called multiple times. Is my usage correct? Is there any way to free the memory before the get pointer of streambuf?


回答1:


asio::streambuf is based on std::vector that grows as needed, but never shrinks. So, consume() is not supposed to release memory, it just adjusts internal pointers:

void consume(std::size_t n)
{
  if (egptr() < pptr())
    setg(&buffer_[0], gptr(), pptr());
  if (gptr() + n > pptr())
    n = pptr() - gptr();
  gbump(static_cast<int>(n));
}

But each time you consume() and read() again, the internal buffer (vector) is reused, so you don't need to release anything.



来源:https://stackoverflow.com/questions/9552785/boost-asio-streambuf-dont-release-memory-after-calling-consume

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!