Jump to content
  • Advertisement
Sign in to follow this  
Grain

Do you find C#'s lack of an explicit destructor to be an issue?

This topic is 1890 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

One of the thing that kind of annoyed me when I first came to C# from C++ was the lack of explicit destructors. I realized that objects are garbage collected, but there are often other resources besides memory that objects can use and sometimes I may want to make the discussion just get rid of an object even though there may be straggling references to it out there some where that prevents the GC from eating it (un-unsubscribed events for example). I find myself adding an abstract virtual "Kill()" method in many of my base classes just to force myself to implement a bit of cleanup later on in my derived classes, like unsubscribing to events.  And then the challenge is to remember to call explicitly Kill() when the time is right.  

 

 

Share this post


Link to post
Share on other sites
Advertisement


You can implement the IDisposable interface and wrap the usage in a using block which ensures that Dispose() is called after the using block is exited.

 

http://msdn.microsoft.com/en-us/library/yh598w02.aspx

Note that this only works within the scope of a function. In programming, it is very common for variables which need explicit cleanup to exist outside of function scope (i.e as a member variable).

 

The common solution to this is similar to when working with Java. Lots of try catches around the place.

 

Interestingly, the memory managed C++/CLR has auto_handle (a clone of auto_ptr for managed references) which effectively does use the IDisposable pattern but works on things like member variables.

 

http://msdn.microsoft.com/en-us/library/ms177065.aspx

 

I looked at the emitted IL and it literally spams the output code with try/fault statements in every function that the variable is used. Basically it seems an elegant solution from a coders point of view, but the underlying system is a tad horrid!

I would actually like to see something like this in C# before I would consider using it for anything other than scripting.

Edited by Karsten_

Share this post


Link to post
Share on other sites

Well, C# does have destructors, you just can't call them. You can however implement and use them as a safety net to make sure that resources are disposed of eventually.

 

Whatever project I'm working on, in the vast majority of cases I either don't care at all when and how an object is cleaned up or care very specifically about the time and exact order an object or data structure is cleaned up. And in this case you need to implement and call the necessary methods yourself anyway. So no, I don't really see any issue there.

 

sometimes I may want to make the discussion just get rid of an object even though there may be straggling references to it out there some where that prevents the GC from eating it

NOT being able to do that is exactly the reason why I prefer C# over C++ for most projects by now.

Share this post


Link to post
Share on other sites
need to implement and call the necessary methods yourself anyway. So no, I don't really see any issue there.

In languages with RAII and "other" solutions to memory management (such as C++ or Objective-C), you indeed need to implement the specialized cleanup code (as you would in C# / Java) (such as send disconnect messages, stop thread etc...) however, you don't need to call the methods yourself. This is extremely important for me because if an exception has been thrown, then in many cases the manual calling of the cleanup code you would need to do in C#, would not be called.

// Pseudo-code/C#: The IDisposable pattern has too much boilerplate for me to be bothered.
MyThread mythread;
 
Constructor()
{
  myThread = new MyThread();
  // oops an exception is thrown
}
 
~Finalizer()
{
  if(myThread != null) { myThread.Destroy(); }
}

void Dispose()
{
  if(myThread != null) { myThread.Destroy(); }
}

The finalizer or Dispose function for a class that never completed its constructor will never be called. You now have a Memory / Resource leak

 

In C++, the thread started by start thread would be destroyed (as the thread object pops off the stack), however in C#, this is made even worse by the fact that the garbage collector will never cleanup the thread because even though it has no reference left, it still has a unit of execution running on it (i.e itself).

 

Again, this can be solved elegantly using either RAII in native C++ or auto_handle in managed C++/CLR

 

In C# or Java, the solution might be something like this (which I personally dont like)

Constructor()
{
  try
  {
    myThread = new MyThread();
    // oops an exception is thrown
  }
  catch(Exception)
  {
    Dispose();
    throw;
  }
}

Ironically when I use Java and C#, I find myself writing more cleanup code than C++ (which admittedly requires none unless you use low-level C libraries (as you would also need to in C#/Java).

Edited by Karsten_

Share this post


Link to post
Share on other sites


The finalizer or Dispose function for a class that never completed its constructor will never be called. You now have a Memory / Resource leak

This is incorrect. The finalizer for a class whose constructor throws an exception will get called. This is because an object has been allocated (regardless of whether the constructor finishes or not) that will, due to the exception, not have any references to it. The garbage collector will see that and call the finalizer.

Share this post


Link to post
Share on other sites

If you write a class that has any IDisposable members, also make that class an IDisposable, and have its Dispose() method dispose all the members. That will emulate destructors in C++, which automatically call members' destructors. Other than that, I can't see what else C# lacks in these regards.

Share this post


Link to post
Share on other sites

I realized that objects are garbage collected, but there are often other resources besides memory that objects can use and sometimes I may want to make the discussion just get rid of an object even though there may be straggling references to it out there some where that prevents the GC from eating it (un-unsubscribed events for example)

This is one of those tarpits I see a lot of devs who are used to C++ fall into. One of the greatest 'eureka' moments in managed languages, is the moment when you learn to work with the garbage collector, rather than against it.

IDisposable is a blunt instrument. You take a shiny new garbage collected language, and you start manually managing your resources, just like everyone had to do 20 years ago in C...

You need to get into a new mindset. Rather than waiting for your clients to inform you they are done with resource, why not track their usage of the resources, and free them up as soon as they stop using them? Why not provide an immediate-mode interface that transparently manages resources behind the scenes?

 

There is no particular reason why developers should have to explicitly manage the lifetime of resources, just as they no longer explicitly manage the lifetime of memory.

Share this post


Link to post
Share on other sites

Hmm. Maybe I can give a better example of what I mean.

 

Lets say there's a basic game entity class, and among it's members is a sprite object. Now there is also a graphics manager class that simply cycles through all existing sprites and draws them to the screen. When an entity is created it hands the graphics manager a reference to it's sprite so it can draw it. Now what happens when that game entity dies. Well lets amuse it's kept track of by a world manager or something like that that does game logic. The the world manager checks if the entity has hit 0 hp and the manager removes it from it's list of living entity and it eventually gets eaten by GC. Now remember that the graphics manager still has a reference to it's sprite, so GC will never touch it. Now the graphics manager just draws that sprite on the screen basically forever even though there's no entity behind it..

 

Now you need write clean up code in the game entity class that makes it go back the the graphics manager and tell it that sprite is no longer valid and it needs to drop its reference to it, and remember to explicitly call that clean up function before throwing the object away.

Edited by Grain

Share this post


Link to post
Share on other sites

If you tell the graphics manager to start drawing a sprite, then logically you should tell it to stop drawing that sprite at some point. Better yet, the graphics manager probably shouldn't be holding on to that reference anyway. You hand the manager a bunch of stuff to draw, it draws that stuff, then clears its references to the drawn stuff.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!