Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The need for C++/CLI finalize destructor

Tags:

c++-cli

Basically, why is there a finalize destructor in C++/CLI. It seems like the GC, before collecting an object, checks to see if delete was called manually and, if not, call the finalizer. So, why can't the GC just call the normal destructor if delete was not called?

like image 211
user119020 Avatar asked Jul 11 '14 02:07

user119020


1 Answers

It is for the same reasons that you have a Dispose method and a Finalizer in C#. Roughly speaking, in C++/CLI, the destructor corresponds to Dispose and the Finalilzer corresponds to the finalizer. I say roughly speaking, because C++/CLI implements the Dispose pattern for you. That is, if delete is called (i.e. the destructor is called), it ensures that the finalizer is suppressed. If delete is not called, then the finalizer will run at GC time.

Just like in C#

  • within the destructor you are allowed to clean-up managed objects and unmanaged objects.
  • within the finalizer you are allowed to clean-up only unmanaged objects because at this point in time (when the garbage collector is running), the other managed object that this object references may have already been cleaned up. Thus, (to answer your question), it would be incorrect for the GC to call the destructor (as the destructor could have code that cleans up managed resources).

If you have a finalizer, it is common (and good practice) for the destructor to call the finalizer.

These two links may help as well:

  • http://msdn.microsoft.com/en-us/library/ms177197(v=vs.90).aspx
  • https://stackoverflow.com/a/12340581/495262
like image 113
Matt Smith Avatar answered Oct 06 '22 01:10

Matt Smith