BOOST :: ASIO :: StreamBuf收缩到合适

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

本文关键字:ASIO StreamBuf BOOST      更新时间:2023-10-16

boost :: asio :: streambuf size size size size size sige dign in nign in comple oferme offem()被调用。

即使调用了消费(),也永远不会释放下面的缓冲区的内存。

例如:以下代码首先创建了streambuf,而无需指定max_size。然后,它将14MB数据转储到StreamBuf中。然后,它消耗所有这些14MB数据。在2000点,streambuf.size()为0,但" top"显示该过程仍为14MB RAM。

我不想指定max_size。无论如何,在溪流是空之后缩小的吗?

#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;
}

所以,我看着来源,在我身上出现了两个观察结果。

  1. 您是对的,缓冲区的实现为STD :: vector,但这是成员是私人的,没有任何登记器。

  2. 消费方法不会触及此字段。

对于您的情况,您应该在消费后销毁缓冲物对象。这是解决问题的最简单方法。出于优化目的,您可以记住最后一个缓冲区的大小,并通过将最后一个大小传递给构造函数,从而用给定容量创建新的缓冲区。您可以围绕此功能编写包装器以获得可读的代码。