On Wed, 11 Apr 2012 13:07:54 -0400, Johannes Pfau <[email protected]>
wrote:
Am Tue, 10 Apr 2012 20:28:28 +0200
schrieb Marco Leise <[email protected]>:
Am Tue, 10 Apr 2012 07:35:31 -0400
schrieb "Steven Schveighoffer" <[email protected]>:
> Destructors are strictly for cleaning up resources that *AREN'T*
> allocated by the GC. For example anything created with C's malloc,
> or an open file descriptor, etc.
This I think is a very good advice to beginners. Short and precise.
It is much more fun to use a new language when you can also free your
mind from some archaic concepts now and then :)
That's a dangerous advice though: You can create lots of file
descriptors without allocating much memory. So in the worst case you
run out of file-descriptors long before the GC calls your destructor.
This is not "dangerous" advice. Freeing resources you own that are not
yet freed is perfectly acceptable, and IMO, good practice. If you own a
resource, and it's not closed manually, you have an obligation to free
it. If you create a class that owns a file descriptor, and don't close it
in the destructor, then it leaves the possibility that you have destroyed
all references to the file descriptor, but left it open, thereby leaking
it.
Yes, it is advisable that when you are creating unlimited numbers of
file-descriptor owning classes, that you manually close them. But the
destructor is a perfectly good place to do that.
I once wrote an application that relied on the GC to close file
descriptors, and it never ran out of file descriptors.
-Steve