Hi,
I am having a hard time understanding the behaviour of finalization. See the attached small code: LinAlg1.F90 (2.2 KB)
Here is the output when running on an arm Mac with gfortran 14.2 ( I get a similar output under linux with the most recent intel compilers).
sibookpro:LinAlg_Class $ ./LinAlg1
Destroying empty
No need to deallocate empty%data
Destroying u
Deallocating u%data
Viewing u
1.00000000 2.00000000 3.00000000 ... 3.00000000
Destroying u
Deallocating u%data
Destroying empty
No need to deallocate empty%data
Destroying v
Deallocating v%data
Viewing v
2.33999991 2.33999991 2.33999991 ... 2.33999991
When the following statement is called
u = LinAlg_Type(‘u’,x)
actually two things occur:
the code inside the function is executed, operating with the internal variable that the function “returns”
assignment from this internal returning variable to the variable “u” declared within main program takes place.
So the “u” is finalized first (before the assignment), the second call is for finalizing the internal variable inside the function.
It helps to realize that when inside the function, the function is not working with the variable “u” because the function “does not know” what happens with the result (It could be used, for example, as an intermmediate in an expression).
That’s correct, but note that the compiler is free to optimize this statement, for instance by not creating a temporary object but rather operating directly on u. In this case a single finalization would occur.
Thanks for all the comments. It looks like gfortran does not allow using subroutines for the constructor while ifx throws an unrelated error. See attached. LinAlg2.F90 (2.4 KB)
No, the standard says that both finalizations occur. In the case there is a final subroutine that needs to be called then this is not an optimization the compiler is free to make.