Fortran Functions with a pointer result in a normal assignment

大憨熊 提交于 2019-12-11 01:23:26

问题


After some discussion on the question found here Correct execution of Final routine in Fortran I thought it will be useful to know when a function with a pointer result is appropriate to use with a normal or a pointer assignment. For example, given this simple function

 function pointer_result(this)
 implicit none 
 type(test_type),intent(in) pointer :: this 
 type(test_type), pointer :: pointer_result 

 allocate(pointer_result)
 end function 

I would normally do test=>pointer_result(test), where test has been declared with the pointer attribute. While the normal assignment test=pointer_result(test) is legal it means something different.

What does the normal assignment imply compared to the pointer assignment?

When does it make sense to use one or the other assignment?


回答1:


A normal assignment

test = pointer_result()

means that the value of the current target of test will be overwritten by the value pointed to by the resulting pointer. If test points to some invalid address (is undefined or null) the program will crash or produce undefined results. The anonymous target allocated by the function will have no pointer to it any more and the memory will be leaked.

There is hardly any legitimate use for this, but it is likely to happen when one makes a typo and writes = instead of =>. It is a very easy one to make and several style guides recommend to never use pointer functions.



来源:https://stackoverflow.com/questions/53976300/fortran-functions-with-a-pointer-result-in-a-normal-assignment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!