使用'delete'及其对传递的局部和变量的影响 [英] Using 'delete' and its effect on local and variables being passed

查看:86
本文介绍了使用'delete'及其对传递的局部和变量的影响的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个功能

I have a function

展开 | 选择 | Wrap | 行号

推荐答案


这里我们使用new为temp分配内存空间。

但是我们没有删除它。

在函数之外的任何地方都没有使用变量temp 。

但是正在使用缓冲区和索引。

我是否应该在此处使用delete for temp?
Here we are allocating memory space for temp using new.
But we are not deleting it.
The varible temp is not used anywhere outside the function.
But buffer and index are being used.
Should I use delete here for temp or not?



指向存储在temp中的缓冲区的指针被复制到Items,因此指针不会丢失,不删除它本身并不是一个问题(它当然可能在程序的其余部分的上下文中是一个问题。)

The pointer to the buffer stored in temp is copied to Items, therefore the pointer is not lost, not deleting it here is not intrinsically a problem (it may of course be a problem in the context of the rest of the program).


变量temp是自动的,这意味着它在例程退出时自动删除。

如果您要求释放在例程中分配的内存(并由temp指向),则在完成内存使用之前,您无法执行此操作。它不会自动释放,所以你必须在某个地方照看那个家务 - 或退出程序。
The variable temp is an automatic, which means it is automatically deleted when the routine exits.

If you are asking about freeing the memory allocated in the routine ( and pointed to by temp ) you cannot do that until you are finished using the memory. It will not be freed automatically, so you have to look after that chore somewhere - or exit the program.



如果你问的是释放例程中分配的内存(并指向temp),在完成内存使用之前,不能这样做。它不会自动释放,所以你必须在某个地方照看那个家务 - 或者退出程序。
If you are asking about freeing the memory allocated in the routine ( and pointed to by temp ) you cannot do that until you are finished using the memory. It will not be freed automatically, so you have to look after that chore somewhere - or exit the program.



到rasmidas:


您无法从指针判断删除它是否安全。它唯一安全的地方就是程序中其他地方没有其他副本。您可以在C / C ++文章论坛中阅读有关Handle Classes的文章。这些智能指针通常用于控制指针的安全删除。

To rasmidas:

You cannot tell from a pointer whether it is safe to delete it. The only time it is safe is when there are no other copies of it anywhere else in the program. You might read the article on Handle Classes in the C/C++ Articles forum. These are the smart pointers that are often used to control safe ddeleting of pointers.


这篇关于使用'delete'及其对传递的局部和变量的影响的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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