必须新的总是后跟删除? [英] Must new always be followed by delete?

查看:72
本文介绍了必须新的总是后跟删除?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我们都明白,当重新分配动态分配的指针时,为了防止内存泄漏,删除的必要性。但是,我很好奇,C ++在什么程度上授权使用delete?例如,采取以下程序

  int main()
{
int * arr = new int [5];
return 0;
}

虽然对于所有意图和目的,和OS将清理所有内存一旦它返回),但标准仍然需要 - 或推荐 - 删除[]在这种情况下的使用?

解决方案

没有什么需要删除[ ] in the standard - 但是,我认为这是一个很好的指南。



但是,最好的做法是使用delete或delete []新的或新的[]操作,即使内存将被程序终止清除。



许多自定义对象将有一个析构函数,记忆。使用delete可以保证在这些情况下的破坏。



此外,如果你移动你的例程,你不太可能导致代码中其他地方的内存泄漏。 / p>

I think we all understand the necessity of delete when reassigning a dynamically-allocated pointer in order to prevent memory leaks. However, I'm curious, to what extent does the C++ mandate the usage of delete? For example, take the following program

int main()
{
     int* arr = new int[5];
     return 0;
}

While for all intents and purposes no leak occurs here (since your program is ending and the OS will clean up all memory once it returns), but does the standard still require -- or recommend -- the usage of delete[] in this case? If not, would there be any other reason why you would delete[] here?

解决方案

There is nothing that requires a delete[] in the standard - However, I would say it is a very good guideline to follow.

However, it is better practice to use a delete or delete[] with every new or new[] operation, even if the memory will be cleaned up by the program termination.

Many custom objects will have a destructor that does other logic than just cleaning up the memory. Using delete guarantees the destruction in these cases.

Also, if you ever move around your routines, you are less likely to cause memory leaks in other places in your code.

这篇关于必须新的总是后跟删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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