简体   繁体   English

std :: queue内存消耗会导致内存泄漏 - C ++?

[英]std::queue memory consumption leads to memory leak - C++ ?

The following codes didn't release the memory consumed for 3000 elements even after i pops out all the elements from the qInt queue. 即使在我弹出qInt队列中的所有元素之后,以下代码也没有释放3000个元素所消耗的内存。 What is the reason ? 是什么原因 ?

std::queue<int> qInt; //Step01: Check the running memory

for (int i=0;i<3000;i++)
{       
    qInt.push(i);
}
//Step02: Check the running memory it should have been increased    

while(!qInt.empty())
{
    qInt.pop();
}
//Step03: Check the running memory expecting Step01 memory but it is still the same of Step02

By defalut std containers do not deallocate memory once they have reserved it. 通过defalut std容器一旦保留它就不会释放内存。 The std::queue is generally implemented on type of std::dequeue which offers shrink_to_fit . std :: queue通常在std :: dequeue类型上实现,它提供了shrink_to_fit If you are not using c++ 11 use the swap idiom . 如果你不使用c ++ 11,请使用交换习语

if you release/free/delete a heap memory . 如果你释放/释放/删除堆内存。 it doesn't mean that the memory consumption will immediately come down . 这并不意味着内存消耗会立即降低。 the memory management libraries have there own caches of free memory which they would release after reaching a threshold . 内存管理库有自己的可用内存缓存,它们会在达到阈值后释放。

First of all the memory used by 3000 integers is very low and can't see a significant change in memory usage if you are checking memory using Task Manager . 首先,3000整数使用的内存非常低,如果使用任务管理器检查内存,则无法看到内存使用量的显着变化。 Also , as explained in other answers the STL containers do not deallocate immediately. 另外,如其他答案中所解释的,STL容器不会立即解除分配。 There is a nice forum discussing memory allocation and deallocation by STL objects and object pointers. 有一个很好的论坛讨论STL对象和对象指针的内存分配和释放。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM