什么时候需要数组解除分配? [英] When is array deallocating necessary?

查看:61
本文介绍了什么时候需要数组解除分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经读到将DEALLOCATE应用于分配的数组会释放它正在使用的空间.我在程序中处理了几个可分配的数组,但是从不去分配它们.是否有一种方法来确定是否/不取消分配会影响执行时间?

I have read that applying DEALLOCATE to an allocated array frees the space it was using. I deal with several allocatable arrays in my program, but never bother deallocating them. Is there a method to determine if/how not deallocating impacts the execution time?

预先感谢

PS:我不倾向于直接进行此测试(通过比较执行时间与不分配情况下的执行时间),因为程序依赖于随机变量,其值最终会影响性能.

PS: I am not prone to do this test directly (by comparing the execution time with and without deallocation) because the program depends on random variables whose values will eventually affect the performance.

推荐答案

确实,释放可以释放变量占用的内存,但并非总是需要您手动进行.

Indeed, deallocation frees the memory occupied by the variables, but not always you need to do it manually.

如果您知道不再需要变量的内容,并且需要释放内存以分配其他变量(或分配给系统),则可以使用deallocate语句.

If you know you won't need the content of the variable anymore AND you need to free up memory for other variables to be allocated (or for the system), you can use the deallocate statement.

但是,当变量超出范围(如@francescalus指出的Fortran 95或更高版本)或到达程序末尾时,将自动发生重新分配.

However, deallocation occurs automatically when the variable goes out of scope (Fortran 95 or later, as pointed by @francescalus) or when you reach the end of the program.

此外,如果数组的维数不一致或变量是多态的并且必须采用一致的动态类型,则在必要时,在分配之前,自动在必要时进行释放. (此行为是Fortran2003或更高版本,在某些编译器上可能需要将其打开.)

Also, deallocation occurs automatically, when necessary, before assignment, if array's dimensions don't coincide or if the variable is polymorphic and have to assume a conformable dynamic type. (This behavior is Fortran2003 or later, and may need to be turned ON on some compilers).

此外,当实际参数与具有属性INTENT(OUT)的虚拟参数相关联时,在进入过程之前会发生释放.

Moreover, when an actual argument is argument-associated with a dummy argument that has the attribute INTENT(OUT), deallocation occur before entering the procedure.

** 警告指针变量:**

如果您明确地为pointer变量分配了存储(使用allocate语句),然后执行了指针关联(=>),则不会自动发生释放.您有责任在执行此操作之前先取消分配该变量,否则会发生内存泄漏.

If you allocated storage for a pointer variable explicitly (with the allocate statement), and after that you perform a pointer association ( => ), deallocation DOES NOT occur automatically. You are responsible for deallocating the variable before doing it or else memory leaks will happen.

最后一点,尝试取消分配未分配的变量会引发错误.您可以检查是否使用内部函数allocated分配了可分配变量.

As a final note, trying to deallocate a variable that is not allocated throws an error. You can check if an allocatable variable is allocated with the intrinsic function allocated.

这篇关于什么时候需要数组解除分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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