Boost :: asio :: streambuf shrink-to-fit?

The size of boost :: asio :: streambuf will continue to grow until a call to () is called.
Even after calling consume (), the memory used by the underlying buffer will never be released.

For example: the following code first created streambuf without specifying max_size. Then it flushes the 14 MB data in streambuf. Then it consumes all this data of size 14 MB. At point 2000, streambuf.size () is 0, but the "top" indicates that the process still takes up 14 MB of memory.

I do not want to specify max_size. Is there anyway to compress streambuf after it is empty?

#include <boost/asio.hpp> #include <iostream> #include <string> int main() { { boost::asio::streambuf b; std::ostream os(&b); for(int i= 0; i<1000000; ++i) { os << "Hello, World!\n"; } std::cout<<"point 1000"<<std::endl; std::cout<<"size="<<b.size()<<std::endl; // at this point, the streambuf size is close to 14MB. b.consume(b.size()); std::cout<<"point 2000"<<std::endl; std::cout<<"size="<<b.size()<<std::endl; // at this point, the streambuf.size() is 0 // but the streambuf underlying buffer, which is a vector I assume, // still hold that 14MB space. // "top" shows the process size is 14M } // at this point, "top" showed the process size shrinks to almost zero std::cout<<"point 4000"<<std::endl; return 0; } 
+4
source share
1 answer

So, I looked in the sources, and two observations seemed to me.

  • You are right, the buffer is implemented as std :: vector, but this member is private and does not have access to it.

  • the consumption method does not apply to this field.

In your case, you must destroy the buffer object after consumption. This is the easiest way to solve the problem. For optimization purposes, you can remember the last buffer size and create a new buffer with a given capacity by passing the last size to the constructor. You can write a wrapper around this function to get readable code.

+2
source

Source: https://habr.com/ru/post/1444251/


All Articles