我使用unordered_map Solaris 10上使用克++ 4.9.2堆,但令人驚訝的我發現清晰()不釋放堆。 這裏的示例代碼:unordered_map:清除()不釋放在明確()
#include <iostream>
#include <unordered_map>
int main()
{
std::unordered_map<long long, long long> mymap;
mymap.rehash(200000);
getchar();
for (int i = 0; i < 2000000; i++) {
mymap[i] = i*i;
}
std::cout << "current bucket_count: " << mymap.bucket_count() << std::endl;
std::cout << "current size: " << mymap.size() << std::endl;
getchar();
mymap.clear();
std::cout << "current bucket_count: " << mymap.bucket_count() << std::endl;
std::cout << "current size: " << mymap.size() << std::endl;
getchar();
return 0;
}
我觀察堆大小的程序時progranm上的getchar等待()。而且,這裏的德堆快照通過pmap -x <PID> | grep heap
1. While waiting on 1st getchar(): `0002C000 792 792 792 - rwx-- [ heap ]`
2. After 1st getchar(): it prints:
current bucket_count: 3439651
current size: 2000000
Heap shows while waiting on 2nd getchar():
0002C000 3920 3920 3920 - rwx-- [ heap ]
00400000 73728 72272 72272 - rwx-- [ heap ]
3. After 2nd getchar(): it prints:
current bucket_count: 3439651
current size: 0
Heap shows while waiting on 2nd getchar():
0002C000 3920 3920 3920 - rwx-- [ heap ]
00400000 73728 72272 72272 - rwx-- [ heap ]
這說明發現(步驟3)明確的()對堆沒有影響。雖然,文檔說,
std::unordered_map::clear
void clear() noexcept;
Clear content
All the elements in the unordered_map container are dropped: their destructors are called, and they are removed from the container, leaving it with a size of 0.
但是,我的堆計數並不反映這一點。 是否有任何其他方式釋放unordered_map對象佔用的堆?或者,我應該使用別的東西嗎? 請指導如何從unordered_map釋放內存?
您從「文檔」中引用的引用沒有說明釋放地圖內部使用的內存,只是地圖將變爲空。這顯然是(因爲你打印尺寸爲零)。 –
我認爲你必須明白大小和容量是有區別的,即使它釋放了用於包含元素的內存,它也不會釋放底層的數據結構。當你調用清除它可能調用析構函數,並設置一些大小變量爲0,但不釋放容器所擁有的內存。 –
從操作系統獲取內存以響應'new'調用返回時,C++運行時庫將不會釋放它,直到該過程結束。 –