From: eric@... (Eric Lee Green) Date: 2001-09-19T04:42:54+09:00 Subject: [ruby-talk:21348] Re: destructor -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Fri, 7 Sep 2001 19:46:37 +0900, Niklas Frykholm wrote: >[Frank Sonnemans] >> Does Ruby have a destructor as in C++? > >Not like that in C++. Since Ruby frees all memory automatic through its >garbage collection, it does not need destructors. I was about to ask this same question. Destructors are useful for more than memory allocation. For example, in a large Python program that I wrote some time ago, there is a class that when instantiated creates several temporary named pipes in /tmp. It has various methods that do various things to those files (such as start up some programs that talk through those named pipes), then it has a has a "cleanup" method to clean up those files, but if the program abends (let's say an exception is thrown) I want those files to go away. Otherwise they hang around in /tmp cluttering things up for days. Not Good. There's another Python class I wrote that creates a pipeline. You feed it various programs in the sequence you want them executed, and it starts them up in the background and returns an (input,output) pipe pair. If the program exits for whatever reason (an unhandeled exception, someone calling exit, etc.), you want to close that pair of pipes so that the pipeline will exit. What you do is Python is create a __del__ method, which is automatically executed by Python when either a) the object is garbage collected (well, Python actually uses a reference counter so the object will be collected immediately after the last reference to it is destroyed), or b) upon exit. So all I do is make the __del__ method check to see if I've already called cleanup (there's a flag), and if not, call cleanup to get rid of those temp files. Voila, no more trash named pipe files hanging around in /tmp (unless the interpreter itself core dumps!). Is there any way I can handle this sort of thing in Ruby? Or do I need to modify all my .initialize functions to shove copies of object instances into a list somewhere and in my main routine catch unhandled exceptions and call the cleanup() methods of all the things on that list? What a pain... Eric Lee Green eric@badtux.org http://www.badtux.org GnuPG public key at http://badtux.org/eric/eric.gpg *** You do not preserve freedom by destroying freedom *** -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE7p5zZ3DrrK1kMA04RAj9YAJ9irC9TEcrihuT3Nv97PFHhRU4/pACfaLB3 KpXj/yK3fjwyyoRqWn9M7bI= =aklW -----END PGP SIGNATURE-----