gpt4 book ai didi

c++ - unordered_map : clear() does not release heap on clear()

转载 作者:行者123 更新时间:2023-11-27 23:56:06 50 4
gpt4 key购买 nike

<分区>

我在 Solaris 10 上使用 g++ 4.9.2 使用 unordered_map,但令人惊讶的是我发现 clear() 不释放堆。这是示例代码:

#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;
}

当程序等待 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 步)clear() 对堆没有影响。虽然,文档说,

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.

但是,我的堆计数并没有反射(reflect)出这一点。有没有其他方法可以释放 unordered_map 对象占用的堆?或者,我应该使用其他东西吗?请指导如何从unordered_map释放内存?

50 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com