c – 为什么编译器推迟std :: list deallocation?

c – 为什么编译器推迟std :: list deallocation?,第1张

概述我有以下代码使用std :: list容器测试内存释放: #include <iostream>#include <list>#include <string>#include <boost/bind.hpp>/* count of element to put into container */static const unsigned long SIZE = 50000000; 我有以下代码使用std :: List容器测试内存释放:
#include <iostream>#include <List>#include <string>#include <boost/bind.hpp>/* count of element to put into container */static const unsigned long SIZE = 50000000;/* element use for test */class Element{public:    Element()    : mID(0)    {}    Element( long ID )    : mID(ID)    {}    virtual ~Element()    {    }    inline long getID() const    {        return this->mID;    }    inline bool operator<( const Element & rightoperand ) const    {        return this->mID < rightoperand.mID;    }    inline bool isEven() const    {        return 0 == ( this->mID & 1 );    }private:    long mID;};typedef std::List< Element > Elements;int main( int argc,char * argv[] ){    std::string dummy;    {        Elements elements;        std::cout << "Inserting "<< SIZE << " elements in container" << std::endl;        std::cout << "Please wait..." << std::endl;        /* inserting elements         */        for( long i=0; i<SIZE; ++i )        {            elements.push_back( i );        }        std::cout << "Size is " << elements.size() << std::endl;        std::getline( std::cin,dummy); // waiting user press enter        /* remove even elements         */        elements.remove_if( boost::bind( & Element::isEven,_1 ) );        std::cout << "Size is " << elements.size() << std::endl;        std::getline( std::cin,dummy);    }    std::getline( std::cin,dummy);    return 0;}

运行此代码为我提供了以下内存配置文件:

看起来gcc正在推迟释放,在我的测试程序中,最终它没有选择并在返回命令行之前释放内存.

为什么解除分配发生得这么晚?

我已经尝试使用矢量来测试另一个容器,并且缩小到适合的技巧可以工作,并在我期望时释放释放的内存.

gcc 4.5.0,linux 2.6.34

解决方法 大多数 *** 作系统(包括linux)只允许进程分配相当大的内存块,而不是非常小的内存;即使有可能,制作许多小型分配比大型分配更为昂贵.通常,C库将从 *** 作系统中获取大块,并使用它自己的堆管理器将它们的一小部分分配给程序.一旦被分割出来,大块通常不会返回到 *** 作系统;它们将继续分配给流程,并将重新用于将来的分配.

List以小块(每个节点一个)分配内存,因此通常在程序退出之前不会释放分配的内存. vector可以直接从 *** 作系统获取其内存作为单个大型分配,在这种情况下,它将在取消分配时释放.

总结

以上是内存溢出为你收集整理的c – 为什么编译器推迟std :: list deallocation?全部内容,希望文章能够帮你解决c – 为什么编译器推迟std :: list deallocation?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/langs/1258279.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-07
下一篇 2022-06-07

发表评论

登录后才能评论

评论列表(0条)

保存