Type constructor and final behavior

A pragmatic solution would be to use an initalization subroutine (or a type-bound procedure) to avoid the pitfalls of overloaded structure constructors and intrinsic assignment.

If you want to use the overloaded-structure constructor for some reason, you could add a variable to your derived type, marking if it’s a temporary. The full pattern is explained in:

Avoiding memory leaks with derived types by Arjen Markus (@Arjen)

This may or may not be suitable because it relies upon using defined assignment (see Should we avoid assignment of derived types in robust programs?).

There is a follow-up article to the one by @Arjen, which also covers nested sub-program invocation:

Stewart, G. W. (2003, December). Memory leaks in derived types revisited. In ACM SIGPLAN Fortran Forum (Vol. 22, No. 3, pp. 25-27). New York, NY, USA: ACM.

As you’ve already noticed, if you’d like to have finalization after each loop iteration, you either need to do it explicitly, or limit the scope of the banana instance to a block within the do construct. The finalization upon assignment is currently not reliable enough if you plan to use multiple compilers.

In case you’re familiar with constructor/destructor semantics in C++, don’t make the assumption that Fortran works similarly.

1 Like