在调用consume()之前,boost::asio::streambuf的大小将继续增加。
即使在调用consume()之后,底层缓冲区使用的内存也永远不会被释放。
例如:以下代码首先创建了一个streambuf,但没有指定max_size。然后它将14Mb数据转储到streambuf中。然后它会消耗所有这些14MB的数据。在点2000,streambuf.size()是0,但是"top“表明进程仍然占用14MB内存。
我不想指定max_size。在streambuf空了之后,有没有办法缩小它?
#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's 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's 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;
}发布于 2012-11-06 16:03:08
因此,我查看了来源,有两个观察结果出现在我面前。
对于您的情况,您应该在消费后销毁buffer对象。这是解决问题的最简单的方法。出于优化的目的,您可以记住上一个缓冲区的大小,并通过将最后一个大小传递给构造函数来创建具有给定容量的新缓冲区。您可以围绕此功能编写一个包装器来实现可读代码。
https://stackoverflow.com/questions/13244287
复制相似问题