Jump to content

  • Log In with Google      Sign In   
  • Create Account


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


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
23 replies to this topic

#1 Grain   Members   -  Reputation: 419

Like
0Likes
Like

Posted 16 August 2013 - 02:20 AM

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.  

 

 



Sponsor:

#2 Paradigm Shifter   Crossbones+   -  Reputation: 5096

Like
7Likes
Like

Posted 16 August 2013 - 03:15 AM

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


"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley

#3 Karsten_   Members   -  Reputation: 1373

Like
0Likes
Like

Posted 16 August 2013 - 03:56 AM



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_, 16 August 2013 - 04:03 AM.

Mutiny - Open-source C++ Unity re-implementation.
Defile of Eden 2 - FreeBSD and OpenBSD binaries of our latest game.


#4 lwm   Members   -  Reputation: 1289

Like
0Likes
Like

Posted 16 August 2013 - 08:17 AM

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.


current project: Roa


#5 Karsten_   Members   -  Reputation: 1373

Like
-1Likes
Like

Posted 16 August 2013 - 09:51 AM

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_, 16 August 2013 - 10:00 AM.

Mutiny - Open-source C++ Unity re-implementation.
Defile of Eden 2 - FreeBSD and OpenBSD binaries of our latest game.


#6 Dave Hunt   Crossbones+   -  Reputation: 2297

Like
0Likes
Like

Posted 16 August 2013 - 11:08 AM


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.



#7 Zipster   Crossbones+   -  Reputation: 545

Like
0Likes
Like

Posted 16 August 2013 - 12:32 PM

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.



#8 swiftcoder   Senior Moderators   -  Reputation: 9544

Like
4Likes
Like

Posted 16 August 2013 - 04:27 PM

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.


Tristam MacDonald - Software Engineer @Amazon - [swiftcoding]


#9 Grain   Members   -  Reputation: 419

Like
0Likes
Like

Posted 16 August 2013 - 06:49 PM

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, 16 August 2013 - 06:53 PM.


#10 Dave Hunt   Crossbones+   -  Reputation: 2297

Like
0Likes
Like

Posted 16 August 2013 - 06:58 PM

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.



#11 Nypyren   Crossbones+   -  Reputation: 3648

Like
1Likes
Like

Posted 16 August 2013 - 08:57 PM

The only time this has been an issue for me was when a different team at work was writing their C#-to-C interop layer and decided it would be a good idea for their interop functions to return C pointers to C#, then use C# finalizers to free the C memory.

This is a bad idea in general, but it would technically work, say, on a desktop PC. The problem was that we were running on an iPhone with extremely limited available RAM. The managed heap and C heap are separate, and the C heap filled up and crashed with an out-of-memory before the C# allocations triggered the GC to execute any finalizers. Whoops.

Due to the way the interop layer was written, IDisposable would have just made the C# side of things excessively hard to manage. The fix was to copy the data over to C# and immediately free the C memory. This caused the desire behavior of the GC kicking in when necessary.



This is a perfect example of what swiftcoder is talking about - When using a managed language, you need to stop trying to manage your own memory. You should insulate as much of the managed layer from unmanaged resource management by enforcing managed behavior as close to the unmanaged code as possible to prevent resource management code from polluting your managed code.

#12 Hodgman   Moderators   -  Reputation: 27084

Like
0Likes
Like

Posted 17 August 2013 - 12:15 AM

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.

I agree that in a managed language, you need to use a different mindset than you do in C/C++/etc, however, I've had a bunch of bugs in my C# tool chain from being lazy with resource lifetimes.
 
e.g. when running my asset build tool, at one point, a file is opened for writing and asset data is written into it. Later on that same file is opened for reading, as another asset is dependent on that data.
If I just open up some streams and trust the GC to clean up my resources, the second open-for-read operation quite often fails, because the open-for-write resource handle hasn't been cleaned up yet. This forces me to either use C#'s using blocks, or to write C-style cleanup code (with the modern twist of doing it in finally blocks, etc). When there are actually requirements on the lifetime of resources, relying on the GC's arbitrary lifetime management doesn't work :/

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.

It's a pretty small change to fix that, from:
m_worldManagerEntities.Remove(sprite);
to:
sprite.Dispose(); // you're dead now, clean up please
m_worldManagerEntities.Remove(sprite);
I personally wouldn't use a design like this in C# or C++ w/ RAII though. You're making the assumption that by removing the sprite from this list, that it will stop being drawn... I'd much prefer this chain-reaction to be stated explicitly, rather than the unwritten assumption that it will just happen by magic.

Now remember that the graphics manager still has a reference to it's sprite, so GC will never touch it.

If you were writing this in C++ with RAII smart pointers, you'd have the exact same problem. You'd solve that problem in both C++ and C# by having your graphics manager use a weak reference.

Edited by Hodgman, 17 August 2013 - 12:19 AM.


#13 Karsten_   Members   -  Reputation: 1373

Like
0Likes
Like

Posted 17 August 2013 - 05:34 AM

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.
 

 

Thats true but check again. This class has a thread running in it. The Finalizer will not be called.


Edited by Karsten_, 17 August 2013 - 05:38 AM.

Mutiny - Open-source C++ Unity re-implementation.
Defile of Eden 2 - FreeBSD and OpenBSD binaries of our latest game.


#14 swiftcoder   Senior Moderators   -  Reputation: 9544

Like
1Likes
Like

Posted 17 August 2013 - 06:10 AM


I agree that in a managed language, you need to use a different mindset than you do in C/C++/etc, however, I've had a bunch of bugs in my C# tool chain from being lazy with resource lifetimes.

I'm not saying be lazy, I'm saying do it the right way.

 

Even in C++, people get this wrong a lot of the time. Abusing shared_ptr because you haven't explicitly defined resource lifetimes, is pretty much evil.


Tristam MacDonald - Software Engineer @Amazon - [swiftcoding]


#15 Grain   Members   -  Reputation: 419

Like
0Likes
Like

Posted 17 August 2013 - 02:27 PM

 


I agree that in a managed language, you need to use a different mindset than you do in C/C++/etc, however, I've had a bunch of bugs in my C# tool chain from being lazy with resource lifetimes.

I'm not saying be lazy, I'm saying do it the right way.

 

Even in C++, people get this wrong a lot of the time. Abusing shared_ptr because you haven't explicitly defined resource lifetimes, is pretty much evil.

 

But I DO explicitly defined resource lifetimes. The struggle is to wrestle with the mechanism by which you get the rest of the code to acknowledge an object is dead. My point is that In a managed language like C# there is extra implementation to be done. 



#16 swiftcoder   Senior Moderators   -  Reputation: 9544

Like
2Likes
Like

Posted 17 August 2013 - 06:28 PM


But I DO explicitly defined resource lifetimes. The struggle is to wrestle with the mechanism by which you get the rest of the code to acknowledge an object is dead.

Either you haven't explicitly defined lifetimes, or you haven't explicitly defined ownership (which goes back to my earlier point, that "shared" is not a valid definition of ownership).

 

If both are explicitly defined, then there cannot be any other code that refers to dead resources.

 

My point is that In a managed language like C# there is extra implementation to be done.

And my point is that you should be doing this implementation in C++, too. Skating by with shared ownership semantics only takes you so far.


Tristam MacDonald - Software Engineer @Amazon - [swiftcoding]


#17 frob   Moderators   -  Reputation: 18427

Like
0Likes
Like

Posted 17 August 2013 - 08:17 PM

This is part of the switch to almost every other language, not just C#.


Many C++-only developers have developed the notion that somehow cleaning up an object and releasing resources are synonymous with destroying an object.

They are not the same.

Many c++ developers simply delete objects without bothering to close them, because they know that the destructor will call the cleanup code if they didn't. That isn't to say most objects are missing cleanup calls; you can close files, release resources, and otherwise clean up objects without destroying them.

Just because c++ destructors also tend to include cleanup code does not mean that cleanup code should never be called elsewhere. Objects should be cleaned up when you are done with them; destruction should clean them up as a failsafe.

It is a bad habit that c++-only programmers tend to get into. Programmers who are used to a wider range of languages generally don't get stuck in that rut.
Check out my personal indie blog at bryanwagstaff.com.

#18 Hodgman   Moderators   -  Reputation: 27084

Like
0Likes
Like

Posted 17 August 2013 - 08:36 PM

I agree that in a managed language, you need to use a different mindset than you do in C/C++/etc, however, I've had a bunch of bugs in my C# tool chain from being lazy with resource lifetimes.

I'm not saying be lazy, I'm saying do it the right way.
If you've got any suggestions for my use case, I'd love to improve my C# code...
n.b. My example was responding to this:

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.


In my build system (like 'make', etc), when building a target, I acquire a variable number of file handles, some read only and some write only, and store them in two lists. I then run the build operation using those two lists, and afterwards have to manually close all those file handles.
This is 'explicitly managing resource lifetimes in a managed language', which apparently is bad (it looks like a C algorithm). In C++ I would set thing up so that when m lists go out of scope, all the handles would be closed.

#19 Promit   Moderators   -  Reputation: 5950

Like
1Likes
Like

Posted 17 August 2013 - 08:55 PM

Swiftcoder's words are far more critical than many people are willing to hear. I used to struggle with C#'s GC behavior a little bit, because it wasn't RAII the way C++ has. But you know what? It's RAII I gave up on. Managing data/memory lifetimes in larger, more coherent blocks with very explicitly designed ownership dispenses with the big problems here, relegating the details to just that, details. Does it work for everything? Not at all. But core game systems work on very rigid, well defined lifetimes. Understand how and when your objects are being used, and make that part of your primary design criteria. Don't vomit GC objects or shared_ptr objects because you have ill defined boundaries of ownership and lifetime.


Edited by Promit, 17 August 2013 - 08:56 PM.


#20 Grain   Members   -  Reputation: 419

Like
0Likes
Like

Posted 17 August 2013 - 09:25 PM


 


But I DO explicitly defined resource lifetimes. The struggle is to wrestle with the mechanism by which you get the rest of the code to acknowledge an object is dead.

Either you haven't explicitly defined lifetimes, or you haven't explicitly defined ownership (which goes back to my earlier point, that "shared" is not a valid definition of ownership).

 

If both are explicitly defined, then there cannot be any other code that refers to dead resources.

 

 

 

My point is that In a managed language like C# there is extra implementation to be done.

And my point is that you should be doing this implementation in C++, too. Skating by with shared ownership semantics only takes you so far.

 

Ok. Object 1 owns object 2. This is explicit. Object 3 has a reference to object 2 because it needs to work with some data it has. Object 1 dies, so it kills object 2 as well.  This is also explicit. 

 

Nowwe still need to inform object 3 that it's reference to object 2 is no longer valid. 


Edited by Grain, 17 August 2013 - 09:26 PM.





Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS