I have a object and simply want to destroy it on some event. How to call the destructor in XNA?
Use the obj. ~ClassName() Notation to Explicitly Call a Destructor Function. Destructors are special functions that get executed when an object goes out of scope automatically or is deleted by an explicit call by the user.
If you run this program and press control-C, you should see the word "destructor" printed. Most signals are catchable as shown above, but not SIGKILL, you have no control over it because SIGKILL is a last-ditch method for killing a runaway process, and not SIGSTOP which allows a user to freeze a process cold.
No. You never need to explicitly call a destructor (except with placement new ). A class's destructor (whether or not you explicitly define one) automagically invokes the destructors for member objects. They are destroyed in the reverse order they appear within the declaration for the class.
Yes, it is possible to call special member functions explicitly by the programmer.
Set the object to null
and the Garbage Collector will pick it up on it's next run.
As a side note, if the object is something that you create often (enemies, bullets etc..), then you may want to use a pool instead of deleting the object. This would mean that object is recycled, and thus, the garbage collector is called less often which will increase performance.
While your mileage may vary, my preference is to use IDisposable
and Dispose()
of objects I no longer need. This is esp. true when you are using unmanaged resources, but having the Dispose()
set up declares intent.
See this resource on GC.SuppressFinalize
for a good example of how to implement IDisposable
.
http://msdn.microsoft.com/en-us/library/system.gc.suppressfinalize.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With