Fortran Functions with a pointer result in a norma

2019-07-13 03:30发布

问题:

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.