Search code examples
.netgarbage-collectionscopec++-clihandles

Is auto_handle still the suggested method for determanistic disposal of handles?


A colleague of mine came across an article on codeproject over the weekend which describes the use of the auto_handle method. Given that the article was written in 2006, is that still the right way to handle deterministic disposal for things like file handles?

We've tended to explicitly flush and close file handles and then delete the pointers and null them to be certain the GC has no excuse not to collect them (yes, we know we're super-paranoid). Using something like auto_handle looks like it could help us be more lazy (and we like being lazy when it's safe to do so) but we don't want to start using it's considered bad practice these days and/or there's something better we can use.


Solution

  • C++/CLI hasn't changed since the 2005 release, so no reason to assume anything new happened. Same advice as was valid back in 2005, auto_handle is not the best way to auto-delete objects. You should consider stack semantics first, it covers the vast majority of cases. The compiler auto-generates the try/finally blocks and the delete call (i.e. disposes the object), equivalent to the C# using statement, minus the code. The example given in the link is done like this:

    void Demo1A()
    {
        StreamWriter sw("c:\\temp\\test.txt");
        sw.WriteLine("This is a line of text");
    }   // <=== Compiler auto-generates the StreamWriter::Dispose call here
    

    Note the missing ^ hat on the object declaration.

    And do consider that this has nothing at all to do with the garbage collector, only with deterministic resource cleanup. Also note that setting local variables to nullptr is very inappropriate, it can extend the lifetime of a reference beyond its actual use unnecessarily. The jitter optimizer removes the assignments.