Version 0 of Playing Strong/Weak References

Updated 2015-07-07 13:41:16 by pdt

With IncrTcl and TclOO, objects must be destroyed manually. If possible, I'd like objects to be cleaned up automatically, for example when a variable holding an object reference goes out of scope at the end of a procedure, or when a variable holding an object reference is set to say "", etc. I also want strong/weak references, to simplify management of objects in certain circumstances.

I've been experimenting with a very simple OO system (owc - objects without classes) to see if I could achieve this, and what I've done so far looks like it works.

Below are three examples, and at the bottom of the page are my sources - a Tcl script that implements owc, and some C code that provides support for strong/weak references.

Example 1

This example is a variation on http://wiki.tcl.tk/20200 .

 
proc ::account::account {{ownerName undisclosed}} {
    set this [ocreate {deposit withdraw transfer} cleanup {
        variables total overdrawLimit owner
    }]
    oset $this total 0 overdrawLimit 10 owner $ownerName
    return $this
}

proc ::account::deposit {amount} {
    ocontext total
    set total [expr {$total + $amount}]
}

proc ::account::withdraw {amount} {
    ocontext total overdrawLimit owner
    if {($amount - $total) > $overdrawLimit} {
        error "Can't overdraw - total: $total, limit: $overdrawLimit"
    }
    set total [expr {$total - $amount}]
}

proc ::account::transfer {amount targetAccount} {
    ocontext total 
    withdraw $amount
    ocmd $targetAccount deposit $amount
    return $total
}

proc ::account::cleanup {} {
    ocontext total
    if {$total} {
        puts "remaining $total will be given to charity"
    }
}

# ------------------------------------------------------------------------------

set a [::account::account "John Doe"]
ocmd $a deposit 200
ocmd $a withdraw 15
puts "a = [oget $a total]"
set b [::account::account]
ocmd $a transfer 65 $b
puts "a = [oget $a total], b = [oget $b total]"
puts "Objects: [ocurrent]"
set a ""
puts "Objects: [ocurrent]"
set b ""
puts "Objects: [ocurrent]"
 

The ocurrent call returns counts of objects by namespace. The output of this script is:

 
a = 185
a = 120, b = 65
Objects: ::account 2
remaining 120 will be given to charity
Objects: ::account 1
remaining 65 will be given to charity
Objects: 
 

As can be seen, setting variables that hold object references to "" result in the objects being cleaned.

Example 2

Example 3

Sources