Re: Destructors are useless?



On Wed, 27 Apr 2005 17:40:26 +1000, Michi Henning wrote:

> Hmmm... That leaves destructors completely useless. There is nothing, not even asserting, that I can do safely.
> Of course, that begs the question: why have destructors when I can't do anything with them? As far as I can
> see, the only legal statements inside a destructor are effectively no-ops.

If you are writing all managed code, then this statement is essentially it.
Within a pure managed environment this is no need to write a destructor.
Destructors are useful for releasing unmanaged resources. The garbage
collector has no specific knowledge on how to clean up an unmanaged
resource. Your class that encapsulates an unmanaged resource does have
that knowledge. So in your destructor you would take the responsibility
for making sure any unmanaged resources are properly released. Let the GC
handle your managed resources.

Also note that adding a destructor unnecessarily to an object can have a
negative impact on performance. An object with a destructor requires at
least two garbage collections. When the GC runs it reclaims the memory for
inaccessible objects without destructors. It cannot, at that time, collect
the inaccessible objects that do have destructors. Instead it places them
in a list of objects that are marked as ready for finalization. It then
calls the finalize method (destructor) on the objects in that list and then
removes them from the list. The next time GC runs it can them collect
these objects as they are now no longer in the list of objects that are
ready for finalization. So the fact that you have added a destructor to
your object only increases the chances that it will hang around longer than
other objects.
--
Tom Porterfield
.



Relevant Pages

  • Re: Life of a thread
    ... > If a thread goes out of scope and the working proc is done ... Unless, of course, you have unmanaged resources (like a database ... IDisposable and add a ~Destructor to handle all unmanaged ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: When a connection closes....
    ... but the destructor is not called until the GC get around to it (which ... by convention, ... resoures implements a Dispose method. ...
    (microsoft.public.dotnet.framework.adonet)
  • Re: Timer disposed before getting to my destructor?
    ... what's a destructor supposed to be used for if I ... I thought the purpose of a ... > Only cleanup which the contained objects can't do for themselves. ... > unmanaged resources directly or indirectly. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Timer disposed before getting to my destructor?
    ... what's a destructor supposed to be used for if I ... I thought the purpose of a ... Only cleanup which the contained objects can't do for themselves. ... unmanaged resources directly or indirectly. ...
    (microsoft.public.dotnet.languages.csharp)

Loading