My AutoPtr class template, which I first published in my article entitled Mixing Native and Managed Types in C++ and then later updated for my MSDN article entitled Best Practices for Writing Efficient and Reliable Code with C++/CLI has turned into quite a popular class while at the same time generating some confusion or frustration.
Most of the trouble seems to come from my finalizer implementation where I insist on using an ASSERT to assure myself that the finalizer is never actually called. The assumption is that the AutoPtr instantiation will only be used internally and my code should never forget to dispose an object containing an AutoPtr. Of course readers have used my class in ways I had not anticipated and not surprisingly have complained that the assertion is firing when the GC calls the finalizer.
As I’ve said before, if you really don’t care about deterministic finalization then by all means go ahead and remove the assertion. It just means that you won’t know when you’re failing to dispose your objects, short of using a profiler or some other technique. Just be warned that relying on finalizers introduces all kinds of other problems so you’re on your own if you choose to rely on the GC to clean up your resources on a regular (irregular) basis.
Anyway, if you want to use the very latest version of AutoPtr you can find it here. This is basically version 3 of AutoPtr and adds some tweaks to previously published versions. Notably, it now throws ObjectDisposedException if you attempt to dereference the pointer. The assertion is still there in the finalizer but you’re free to comment it out if you really want to. Of course the ASSERT macro should be preprocessed to nothing in release builds, assuming your ASSERT macro is defined correctly, so it shouldn’t cause a problem for release builds that you may distribute.
© 2007 Kenny Kerr