Std :: deque在程序退出之前不会释放内存 [英] Std::deque does not release memory until program exits

查看:258
本文介绍了Std :: deque在程序退出之前不会释放内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在linux上,std :: deque在程序退出之前不会释放内存。完整的代码如下。

On linux, std::deque does not release memory until program exits. The complete code is below. Any help will be greatly appreciated!

#include <deque>
#include <vector>
#include <string>
#include <iostream>
#include <boost/shared_ptr.hpp>
#include <queue>
#include <list>
#include <cstdio>
#include <cstdlib>

typedef  boost::shared_ptr<std::vector<int> > VecPtr;
typedef  std::deque< VecPtr  > QueueType;

 char buf[1024];
 char line[1024];

 int main()
 {

  {

    int v=0;
    QueueType  deq;
    for(int i=0; i<30;++i)
    for(int j=0; j<1000;++j)
    for(int k=0;k<1000;++k)
    {
       VecPtr p( new std::vector<int>);
       deq.push_back(p);
    }

    std::cout<<"Done with increasing deq:deq size="<<deq.size()<<std::endl;
    sleep(20);

    std::cout<<"start decreasing deq size"<<std::endl;
    while(deq.size()>0)
    {
      deq.pop_front();
    }
    std::cout<<"done with decreasing deq size,deq size="<<deq.size()<<std::endl;
  }
  std::cin.getline(line,sizeof(line));
  return 0;
}


推荐答案

那是正确的, pop_front()不会取消分配由 push_back()
分配的存储空间。程序结束后,可以结束对象的生命周期。如果要在对象的生存期结束之前对其进行分配,请考虑使用 适用于C ++容器类的紧缩习惯

That is correct, pop_front() does not deallocate storage that was allocated by push_back() If you want to deallocate it before the program ends, you can end the lifetime of the object. If you want to deallocate it before the lifetime of the object ends, consider using a "shrink-to-fit" idiom for C++ container classes.

QueueType().swap (deq); // C++98
deq.shrink_to_fit(); // C++11

这篇关于Std :: deque在程序退出之前不会释放内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆