如果我不“删除"会发生什么? [英] What happens if I don't 'delete'?

查看:70
本文介绍了如果我不“删除"会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在执行期间分配了一些内存但从不调用 delete 并且程序终止会发生什么?操作系统会释放我分配的所有内存并且不会浪费"内存吗?还是会在重新启动计算机之前丢失一部分内存?

What happens if I allocate some memory during execution but never call delete and the program terminates? Will the OS free all memory I allocated and no memory will be 'wasted'? Or will I lose a portion of memory until the computer is restarted?

显然,我知道良好的编码习惯是确保删除不需要的内容,所以我不只是问delete 有什么意义";我只是想知道我的 RAM 中发生了什么.

Obviously I know good coding practice is to make sure you delete what you don't need, so I'm not just asking "what is the point of delete"; I'm simply interested to know what happens inside my RAM.

推荐答案

这完全取决于您的程序做什么,以及它使用了多少内存 - 在任何给定时间和整个运行时的整体.

It all depends on what your program does, and how much memory it uses - at any given time and overall throughout its runtime.

比如说你写了一个邮件服务器,它分配内存来保存它收到的每封电子邮件.但它实际上并不需要存储通过它的每封电子邮件.因此,在接收和转发电子邮件几天后,邮件服务器无法分配更多内存,它已经消耗了所有可用的内存字节 - 但它实际上并没有对这些内存做任何有用的事情,因为电子邮件不再使用- 他们已经被处理了.

Say for example you write a mail server, that allocates memory to hold each email it receives. But it doesn't actually need to store every email that goes through it. So after a few days of receiving and forwarding emails, the mail server can't allocate any more memory, it has consumed every available byte of memory - but it's not actually doing anything useful with that memory, since the emails are no longer in use - they have been dealt with.

另一方面,如果我们编写邮件服务器程序,例如分配 1 MB 的缓冲区来读取电子邮件、处理它,并在完成后将内存重新用于另一封电子邮件,那么几乎没有永远要释放那个内存.

On the other hand, if we write our mail server program that allocates, say, 1 MB of buffer to read in an email, process it, and when it's done with, the memory is reused for another email, then there's little point in freeing that memory, ever.

如果我们编写一个程序,只读取一个文件,将整个文件加载到内存中,当它统计所有字母时,打印统计信息并退出,无论是否分配了大量内存都没有没关系.

And if we write a program that just reads a file, loading the entire file into memory, and when it has counted all the letters for statistical purposes, prints the stats and exits, whether that allocates a lot of memory or not doesn't really matter.

当然,所有这些都假设对 new 的调用只是为了分配内存.如果对象的构造函数做了一些更复杂的事情,比如打开文件、获取锁或其他什么,那么如果不调用析构函数,各种坏事很快就会发生.

Of course, all this assumes that the call to new is SIMPLY to allocate memory. If the constructor of the object does something more complex, like open a file, acquire a lock or something else, then all sorts of bad things could happen pretty soon if the destructor isn't called.

操作系统将(对于常用的操作系统,如 Linux、macOS、iOS、其他 Unix 系统、Windows、DOS、OS/2 等)释放您的应用程序使用的内存.

The OS will (for the commonly used OS's such as Linux, macOS, iOS, other Unix-systems, Windows, DOS, OS/2, etc) free the memory used by your application.

这篇关于如果我不“删除"会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆