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

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

问题描述

我已经读到将 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.

推荐答案

确实,deallocation 会释放变量占用的内存,但并不总是需要手动执行.

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 allocated object 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天全站免登陆