c++ - 为什么删除和清除所有对象后内存没有返回系统?
问题描述
#include <chrono>
#include <cstdio>
#include <list>
#include <thread>
struct a {
char data[1024];
};
struct b {
char data[1024];
};
struct c {
char data[1024];
};
struct d {
char data[1024];
};
int main() {
std::list<a *> a_list;
for (size_t i = 0; i < 1000000; i++) {
a_list.push_back(new a);
}
std::list<b *> b_list;
for (size_t i = 0; i < 1000000; i++) {
b_list.push_back(new b);
}
std::list<c *> c_list;
for (size_t i = 0; i < 1000000; i++) {
c_list.push_back(new c);
}
std::list<d *> d_list;
for (size_t i = 0; i < 1000000; i++) {
d_list.push_back(new d);
}
printf("---\n"); // line A
while (a_list.size() > 0) {
a *item = a_list.front();
a_list.pop_front();
delete item;
}
printf("---\n");
while (b_list.size() > 0) {
b *item = b_list.front();
b_list.pop_front();
delete item;
}
printf("---\n");
while (c_list.size() > 0) {
c *item = c_list.front();
c_list.pop_front();
delete item;
}
printf("---\n");
while (d_list.size() > 0) {
d *item = d_list.front();
d_list.pop_front();
delete item;
}
printf("end\n"); // inline B
std::this_thread::sleep_for(std::chrono::hours(1));
}
在 A 行,进程内存使用率为 26%。在 B 行,进程内存使用率为 26%!
为什么会这样?
更多案例:
当我删除
b
,c
和d
and just leavea
时,结果是一样的。
如果我将a
数组的长度设置为130000
,结果是一样的,但是当我将它增加到 140000 时,结果就不同了:内存实际上被释放了。在空闲行之后,我添加了更多代码以使用 为更多项目分配更多内存
new
,然后内存使用量上升,但分配的字节数比第一次少。
解决方案
注意:这不是我的答案,我是从 MX 的评论中引用的。Andrieux“不需要一个进程将释放的内存返回给操作系统,它可以保留它以便以后更快地分配。”
我确信该程序将在关闭程序后返回所述内存。尽管程序创建的任何文件在关闭程序后都将保留在磁盘内存中。
推荐阅读
- php - Laravel 活动日志使用 Ajax Jquery 分页
- oracle - HikariCP 显示不可用的连接,而数据库没有运行会话 - 如何找到原因?
- laravel - preg_match():编译失败:偏移量 20 处的字符类范围无效
- r - sankey plot R不显示降价
- json - 如何使用 powershell 脚本从 Url 中提取 json 数据
- file - 从代码输出保存到文件时遇到问题
- emacs - 附加到 emacs-lisp 中列表的默认值:具体来说,dotspacemacs-configuration-layers
- laravel - 如何使用 JavaScript 从 Firebase 中删除图像?
- javascript - toLocaleDateString() 不适用于哈萨克斯坦语言
- javascript - 角度可编辑文本