I am using unordered_map using g++ 4.9.2 on Solaris 10, but surprisingly I found that clear() does not release heap. Here's the sample code:
#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;
}
I am observing heapsize for the program when the progranm is waiting on getchar(). And, here's teh heap snapshot found through 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 ]
This shows (step 3) that clear() has no impact on heap. Although, the documentation says,
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.
But, my heap count does not reflect that. Is there any other way to release heap occupied by unordered_map object? Or, should I use something else? Please guide how to release memory from unordered_map?