Search code examples
ooptclinstancedestroy

Do I need to explicity destory an instance of 1 class which is within an instance of a 2nd class in Tcl


let's assume that I have class1, created by oo::class create

oo::class create class1 {
   method bar {} {
      class2 create bee
      bee method1
   }
}

Now, let's say that I have this code:

class1 create po
po bar
po destroy

Am I destroying also the instance bee within po, or should I also explicitly destroy po::bee?
Thanks.


Solution

  • The create method of oo::class prefers to resolve names of objects it is creating with respect to the current namespace (i.e., if they're not absolute names). That means that when you call it inside a method of another object with an unqualified name, the object it creates will be put inside that other object. (You can verify this by examining the result of the create method, which is the fully-qualified name of the created object for ordinary classes.) In turn, that means that when the outer object is destroyed, the inner objects will also be destroyed when the outer object's instance namespace is deleted and the commands inside it are killed off.

    Let's demonstrate by using some simple classes:

    oo::class create Inner {
        destructor {
            puts "Hi from an Inner"
        }
    }
    oo::class create Outer {
        method makeAnInner {} {
            puts [Inner create in]
        }
        destructor {
            puts "Hi from an Outer"
        }
    }
    Outer create out
    out makeAnInner
    out destroy
    

    That prints something like (the namespace name will vary) this:

    ::oo::Obj19::in
    Hi from an Outer
    Hi from an Inner
    

    However, it is often better to call the inner object's destroy method more directly, since then any errors that occur in the destructor won't get discarded. (With the other destruction scheme, the current internal API can't safely preserve error reporting for various ugly reasons, especially as that's also a deletion route that is used at times when much more extensive deletion is occurring.)