# Finalization ifort vs gfortran

**URL:** <https://fortran-lang.discourse.group/t/finalization-ifort-vs-gfortran/7816>\
**Category:** Uncategorized\
**Created:** [April 11, 2024, 1:34pm UTC](https://fortran-lang.discourse.group/t/finalization-ifort-vs-gfortran/7816 "2024-04-11T13:34:43Z")\
**Posts on this page:** 1\
**Showing post:** 12

<div class="post-metadata">

**Author:** ![ivanpribec](https://yyz2.discourse-cdn.com/free1/user_avatar/fortran-lang.discourse.group/ivanpribec/32/3290_2.png) [@ivanpribec](https://fortran-lang.discourse.group/u/ivanpribec)\
**Post date:** [April 12, 2024, 11:53am UTC](https://fortran-lang.discourse.group/t/finalization-ifort-vs-gfortran/7816/12 "2024-04-12T11:53:40Z")

</div>

I’ve encountered this problem before, where the finalizer works “earlier” than you expect it too.

```auto
type :: holds_pointer
   type(c_ptr) :: handle = c_null_ptr ! points to heap memory
contains
   final :: shutdown ! releases the handle
   procedure :: use_handle
end type

type(holds_pointer) :: instance

instance = create_instance()
call instance%use_handle() ! KA-BOOM! (Invalid handle)

```

The problem is really not the finalizer, but the fact that object creation, destruction, and copying are tightly linked operations. In C++ they call this [the rule of three](https://en.wikipedia.org/wiki/Rule_of_three_(C%2B%2B_programming)#:~:text=The%20rule%20of%20three%20) or “the big three”. Quoting Wikipedia, the rule claims that if a class defines any of the following then it should probably explicitly define all three:

- destructor
- copy constructor
- copy assignment operator

Fortran doesn’t have such a thing as a copy constructor. You could fix the problem by overloading the assignment operator, but this has it’s own subtle problems (i.e. does the assignment perform a deep copy or a shallow copy of the pointer?).

There are (at least) two ways to fix this:

- avoid assignment; use an initalizer subroutine or a type-bound procedure (as shown by @davidpfister) instead
- wrap the pointer in a derived type with defined assignment as explained here: [Should we avoid assignment of derived types in robust programs? - #35 by FortranFan](https://fortran-lang.discourse.group/t/should-we-avoid-assignment-of-derived-types-in-robust-programs/2359/35)

---

_[View the full topic](https://fortran-lang.discourse.group/t/finalization-ifort-vs-gfortran/7816)._
