Updated 2012-09-08 16:26:25 by LkpPo

I was concerned about leftover itcl class object instances at program termination. The following code fragment just before exit will identify any class objects still in existence.
  proc exitprogram {} {
        set rems [itcl::find objects * ]
        if {[llength $rems]>0} {
            tk_messageBox -message "At end of run undestroyed objects remain: $rems"

You can then decide where these objects should have been deleted (leaving them to the end and deleting the list $rems is a memory leak).

My itcl programs use a 'main object' to hold the entire program (menus, tool bars etc), and the main object holds a number of objects representing single cases (e.g. a file editor allows several files to be edited at once, so you get one itcl object per open file). Each case allocates further objects (perhaps one per paragraph) and so on (the paragraphs may contain a list of sentences....). This structure allows the order of the objects to be changed at will, and allows very simple objects at the base (perhaps a single word!). The classes then handle 'save to a file' by calling the case method 'savetofile' which calls paragraph::savetofile for each paragraph, each paragraph calls word::savetofile.... the result is a tree of objects, and in a well written program, deleting a sentence will delete all the 'word' objects. Closng a case (one file) will delete all the paragraphs (which delete the sentences, which delete the words). Naturally this is all built into the destructor method of each object.

It is good practice to delete all objects at the end of a program and to delete related objects when closing a document/case. undelted objects are called memory leaks and running a leaking program for a long time could result in the gradual build up of orphaned objects, filling up memory, slowing your program (and ultimately your whole computer).

The above code will detect orphaned objects at the end of a run. I have similar routines for whenever I close a case - I ensure that all the paragraph objects are named "$case.p#auto" and the sentences in a paragraph "$case.p#auto.s#auto". When a case is closed similar code to the above checks:
        set rems [itcl::find objects $case.* ]
        if {[llength $rems]>0} {
            tk_messageBox -message "At end of $case undestroyed objects remain: $rems"

Talking about memory leaks in [incr Tcl] -- a base class does not get destructed when a derived class has the same name (but in a different namespace). A patch can be found at [1]. This bug still exists in the latest releases as of November 2006.