The user_object_smart_pointer.f90 file demonstrates the use of Smart-Pointers, including
- A module that defines
user_object_t
anduser_object_ptr_t
types, - A submodule defining a constructor funciton and a
free
final subroutine, - A main program with a
block
construct that causes finalization of theuser_object
when the program reaches theend block
statement.
This example exhibits several important subtleties:
- Smart-Pointers automate object finalization, eliminating the need
for
allocatable
objects. - The main program source-allocates a raw
user_object
pointer and then passes the pointer to auser_object_ptr_t()
constructor. - The
user_object_ptr_t()
constructor nullifies the received pointer to encourage the intended practice in which all pointers associated with the object are reference-counted pointers. - All assignments in the main program and its internal subroutine
perform shallow copies, thereby creating new references to
user_object
without copying the object.
With gfortran
13.0.1 20230321 or later in your PATH
, run the example
as follows:
fpm run --example user_object_smart_pointer
or with the NAG Fortran compiler in your PATH
, use
fpm run --example user_object_smart_pointer --compiler nagfor --flag -fpp
either of which should produce the following output:
Allocating user_object pointer.
Defining smart_pointer_1.
Reference count = 1
Copying smart_pointer_1 into smart_pointer_2.
Reference count = 2
Copying smart_pointer_2 into smart_pointer_3.
Reference count = 3
smart_pointer_3 going out of scope.
Reference count = 2
smart_pointer_1 and smart_pointer_2 going out of scope
free(): user_object deallocated