The user_object_smart_pointer.f90 file demonstrates the use of Smart-Pointers, including
- A module that defines
user_object_tanduser_object_ptr_ttypes, - A submodule defining a constructor funciton and a
freefinal subroutine, - A main program with a
blockconstruct that causes finalization of theuser_objectwhen the program reaches theend blockstatement.
This example exhibits several important subtleties:
- Smart-Pointers automate object finalization, eliminating the need
for
allocatableobjects. - The main program source-allocates a raw
user_objectpointer 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_objectwithout 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