• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
Grain

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

23 posts in this topic

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.  

 

 

0

Share this post


Link to post
Share on other sites


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_
0

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.

0

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_
-1

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.

0

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.

0

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
0

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.

0

Share this post


Link to post
Share on other sites
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.
1

Share this post


Link to post
Share on other sites

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
0

Share this post


Link to post
Share on other sites

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_
0

Share this post


Link to post
Share on other sites


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.

1

Share this post


Link to post
Share on other sites

 


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. 

0

Share this post


Link to post
Share on other sites


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.

2

Share this post


Link to post
Share on other sites
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.
0

Share this post


Link to post
Share on other sites

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.
0

Share this post


Link to post
Share on other sites

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
1

Share this post


Link to post
Share on other sites

 


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
0

Share this post


Link to post
Share on other sites

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.

 

The two statements marked in bold both represent potential problems with this design:

- Object 1's lifetime is non-deterministic by virtue of being garbage collected, so by tying object 2's lifetime to object 1, you have made object 2's lifetime non-deterministic as well.

- If object 3 stores a reference to object 2, then it has assumed co-ownership of object 2, and object 2 can no longer be solely tied to object 1's lifetime.

 

There are a couple of questions that are worthwhile to ask at this point:

- Why is the lifetime of object 2 tied to that of object 1, instead of being tied to program lifecycle events (i.e. level unload, application shutdown, etc)?

- Why does object 3 store a reference to object 2? Is the a concrete reason why it could not be passed that reference each time it needs access to the data?

- Why cannot object 3 maintain a reference to object 1 instead?

1

Share this post


Link to post
Share on other sites

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.

if you know ahead of time that the lifetime of #3 is shorter than #1/#2, then there's no problem (in debug builds, I'd use a weak reference and assert that it is never nullified).
If you know that the lifetime of #3 is longer than #2, then the ownership definition may be wrong.
If the lifetimes of #1 and #3 are arbitrary and unrelated, but you want to detach the link between #3/#2 when #1 dies, then use a weak-reference / weak-pointer, or write this behavior explicitly if it's regular business logic instead of resource management ;)
0

Share this post


Link to post
Share on other sites
There was an sprite-drawing-example similar to the 3 objects.
I don't see any problems in drawing sprites in C# (or Python, or Java, ...).
In general you will have some kind of ingame environment, eg. a map, a level, a room, or something else. This environment contains all the objects you want to draw, walls, tables, charakters, items, mosnters, and so on. So why don't you try to draw the environment and store the sprites seperated?
There are also other problems arising out of this bad design: the player opens a door and an other sprite has to be drawn at the same position, the player starts walking, the player hides and gets invisible, an item explodes and there has to be some kind of explosion effect, or the drawing order changes (because the player walked behind a wall).
This way you would have to add and remove sprites all the time. By drawing the environment you could always use the objects current states and removing(/destroying) an object is no problem.
0

Share this post


Link to post
Share on other sites

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.

I am a bit confused about how you think C++ handles this any better than C#?

If Object 3 and Object 1 owned shared_ptrs to Object 2 then you'll have the same cleanup considerations as with C#.
If Object 3 owned a weak_ptr then C# has those too, but with a non-deterministic GC I wouldn't bother, nor would I go that route in C++ either.
If Object 3's lifetime or its reference to Object 2 is short, transient or non-owning (e.g. you re-pass Object 2 along every frame), then you can do that in C# as well.

The only thing I can think at the moment is that your destructor of either Object 1 or Object 2 will call directly into Object 3 to unregister Object 2? If so you have still had to put that 'extra implementation' into C++ too, only in a destructor. Hopefully Object 3 would never through an exception during that unregistering.

A C++ destructor (or C# IDisposable) is really about cleaning up raw resources within that object - not about supporting your business logic to unregister it from the rest of the system. Edited by dmatter
1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0