Thursday, May 5, 2011

Smart pointers and error handling

Today I worked on the systems.  Like I mentioned in yesterday's blog post, I have decided to take a reference counting approach to this problem.  My original thought was to create and destroy the systems from within the application layer, and share these with the game states.  With the new design though, there is a game state called "Initialize" which creates the systems.  These systems are then passed between game states via their input structures.  If a system isn't passed, the reference counter will notice that nothing is referencing it anymore and will remove it.  This makes shutting down simple since the systems will be destroyed when the last game state is left.

While I was at it, I decided to wrap the current state interface and input structure into smart pointers.  These pointers are only used within the main loop, and there is only one copy of them, so I used a variety of smart pointer called "scoped pointer".  A scoped pointer only allows one reference to the pointer, which means that creating a copy of the pointer, assigning the pointer to something, and passing the pointer as a byval argument to a function is not allowed.

My main reason for using smart pointers is that I use exceptions for error handling.  One of the big drawbacks (in my opinion) to using exceptions for error handling is that everything which must do something before the program is shutdown (allocated memory must be deallocated, window classes must be unregistered, DirectX COM interfaces must be released...) needs to be placed inside of an object.  When an exception is thrown, the destructors of created objects are called, thus allowing you to clean things up.  Using smart pointers is a generic way of doing this for allocated memory.  Things such as a window class or a DirectX COM interface need specialized classes though.

No comments:

Post a Comment