Type-bound generics and finalisers

A type usually wants one name for an operation that has several forms, and one last piece of code that runs when a value dies. Both are bindings: generic makes one name stand for several procedures, and final binds a procedure to the end of the object. This lesson gives a running total two ways of adding to it behind one name, runs a finaliser that reports what it saw, and reads the error of a generic whose two forms cannot be told apart.

A generic binding

generic :: add => add_value, add_array puts two specifics behind one name in the type. A call a%add(1.0) picks add_value because the second argument is a scalar, and a%add([2.0, 3.0, 4.0]) picks add_array because it is a rank-one array. The object in front of the percent sign is the same in both.

The file gen.f90:

module accs implicit none private public :: acc type :: acc real :: total = 0.0 integer :: count = 0 contains procedure, private :: add_value procedure, private :: add_array generic :: add => add_value, add_array procedure :: mean => acc_mean final :: acc_final end type acc contains subroutine add_value(self, x) class(acc), intent(inout) :: self real, intent(in) :: x self%total = self%total + x self%count = self%count + 1 end subroutine add_value subroutine add_array(self, a) class(acc), intent(inout) :: self real, intent(in) :: a(:) self%total = self%total + sum(a) self%count = self%count + size(a) end subroutine add_array function acc_mean(self) result(m) class(acc), intent(in) :: self real :: m m = self%total / self%count end function acc_mean subroutine acc_final(self) type(acc), intent(inout) :: self print '(a,f6.1,a,i0)', ' finalizer: total = ', self%total, ' count = ', self%count end subroutine acc_final end module accs program gendemo use accs implicit none call run() contains subroutine run() type(acc) :: a call a%add(1.0) call a%add([2.0, 3.0, 4.0]) print '(a,f8.2)', 'total = ', a%total print '(a,f8.2)', 'mean = ', a%mean() end subroutine run end program gendemo

gfortran -Wall -Wextra -std=f2018 gen.f90 -o gen
./gen

total = 10.00
mean = 2.50
finalizer: total = 10.0 count = 4

The two calls added four numbers to one total, and mean divided by the count of them. The third line comes at the end because the record a went out of scope when run returned: the finaliser printed after every ordinary statement of the program.

Private specifics

The two specifics are procedure, private and the generic is not, so a user of the module sees %add and cannot call %add_value or %add_array at all. That is the point of a generic: the name that a caller writes is one promise, and the number of procedures behind it is the module's business. A later round can add a third specific, for a rank-two array or a double-precision value, without changing any caller.

The resolution rule is the same as for a plain generic interface: the compiler matches the types, kinds and ranks of the actual arguments against the specifics and requires exactly one match. The passed-object dummy is not part of the match for a plain binding, since it is the same object either way.

FINAL and the finaliser

final :: acc_final binds a subroutine that the runtime calls when a value of the type is destroyed. Its only dummy is the object, declared type(acc), intent(inout): not class(acc), because a finaliser of a parent type is not what runs for a child, and not intent(in), because the object is on its way out and the finaliser may still copy from it.

A finaliser is where a resource a type holds is released: a file unit it opened, a C pointer it allocated, a count it keeps in a module. In a program like this one it is also the cheapest way to see the order of the events, which is why the example prints instead of closing anything.

When a finaliser runs

The standard names the four occasions: when a variable of the type goes out of scope, when an allocatable of the type is deallocated, when a value is assigned over, and when a non-pointer dummy with intent(out) is entered. The example shows the first. Two of the others are worth remembering because they surprise people: a = acc(...) destroys the old value of a first, and entering a subroutine with an intent(out) record destroys whatever the caller had in it before the first statement of the subroutine runs.

A finaliser is not a destructor in the C++ sense in one respect: it is not called for a value that was never constructed. A variable that is declared and never assigned has its default components, and its finaliser runs at the end of its scope like any other.

One behaviour of this build is worth knowing before relying on a finaliser for a file handle. The record of the example lives in the contained subroutine run, and its finaliser runs when run returns. The same record declared in the main program is not finalised at all by gfortran 15.2.0: the program ends and the finaliser of a main-program variable never runs. A program that depends on a finaliser for its last writes should keep the values in a procedure rather than at the top level, or close them explicitly.

An ambiguous generic

Two specifics that accept the same arguments make the generic unusable, and the compiler says so where the generic is declared:

module accs implicit none type :: acc real :: total = 0.0 contains procedure :: add_value procedure :: add_real generic :: add => add_value, add_real end type acc contains subroutine add_value(self, x) class(acc), intent(inout) :: self real, intent(in) :: x self%total = self%total + x end subroutine add_value subroutine add_real(self, x) class(acc), intent(inout) :: self real, intent(in) :: x self%total = self%total + 2.0 * x end subroutine add_real end module accs program amb use accs implicit none type(acc) :: a call a%add(1.0) print *, a%total end program amb

gfortran -Wall -Wextra -std=f2018 e1.f90 -o e1

e1.f90:8:21:

8 | generic :: add => add_value, add_real
| 1
Error: 'add_value' and 'add_real' for GENERIC 'add' at (1) are ambiguous
e1.f90:24:7:

24 | use accs
| 1
Fatal Error: Cannot open module file 'accs.mod' for reading at (1): No such file or directory
compilation terminated.

The second error follows from the first and is worth knowing: a module that fails to compile leaves no .mod file behind, so the program that uses it cannot be compiled either, and the message about a missing module file is a symptom rather than the problem. The row to fix is the first one.

The fix is to give the second specific an argument the first cannot take: a rank-two array, an integer, or a second real with a different meaning. Two procedures that take the same arguments and do different things are two procedures, and one of them needs a name of its own.

What a finaliser costs

A type with a finaliser is not trivially copyable in the compiler's eyes: an array of it, an assignment, or a call that passes it by value has to run code per element. gfortran generates that code, and for a record of a few reals the difference is small. For a type used in a hot loop it is a cost to measure rather than assume, and the measurement is lesson 121.

The other cost is a design one. A finaliser that prints, writes a file or changes a module variable makes the end of a scope observable, and the order in which two variables of the same scope are finalised is not specified. Use it to release what the type owns, and leave everything else to the program.

Exercises

  1. Add a third specific add_matrix for a rank-two array to the generic %add. Does the generic need a new line?
  2. Call a%add_value(1.0) from the program. What does the compiler say, and why?
  3. In run, write a = acc(5.0, 1) after the two calls. Which finaliser line appears before the assignment takes effect?
  4. Make the finaliser take class(acc) instead of type(acc) and read the error. What does the message say the type of the dummy must be?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does generic :: add => add_value, add_array inside a TYPE do?

    Answer

    One binding name stands for both procedures; the call picks by argument type

    The passed object is the same in both, so the arguments decide.

  2. Why are the specifics declared procedure, private?

    Answer

    So callers use the one generic name and the split stays internal

    The generic is the promise; the specifics are the implementation.

  3. What is final :: acc_final?

    Answer

    A binding of a subroutine that runs when a value of the type is destroyed

    It is the finaliser of the type.

  4. What does this program print? module m implicit none type :: box integer :: n = 0 contains final :: bye end type box contains subroutine bye(self) type(box), intent(inout) :: self print *, "bye", self%n end subroutine bye end module m program p use m implicit none type(box) :: b b%n = 3 print *, "alive", b%n end program p

    Answer

    alive 3

    The record lives in the main program, and this gfortran does not run its finaliser at termination; inside a subroutine it does.

  5. How is the dummy of a finaliser declared?

    Answer

    type(t), intent(inout)

    The object is being destroyed and may still be read.

  6. Which of these does NOT call a finaliser?

    Answer

    Reading a component of the record

    Reading does not destroy anything.

  7. What does gfortran report for two specifics that take the same arguments?

    Answer

    Error: ... for GENERIC ... are ambiguous

    No call could choose between them.

  8. Why does a second error about a missing module file follow an ambiguous generic?

    Answer

    The module did not compile, so no .mod file was written

    A failed module leaves nothing for the program to read.

  9. What is the main risk of a finaliser with side effects?

    Answer

    The order between two variables of the same scope is not specified

    Release resources; leave observable work to the program.

  10. What does a type with a finaliser cost?

    Answer

    Code runs per element on destruction and on assignment

    The compiler generates finalisation code where values die.

The programs on this page were built with GNU Fortran (Alpine 15.2.0) 15.2.0 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev