> Commenting out the print removes the reference to %wids which makes
> "sub {...}" just return a constant that lives in perl's OP-tree.  It
> is only when there are references to outer lexicals that "sub {...}"
> returns a fresh CV each time it executes.

good catch; now I no more thinking of this as of a mysterious case...

> 
> Compare the output of these:
> 
>    perl -le 'my $a = 1; print map sub { $a }, 1..3'
>    perl -le '   $a = 1; print map sub { $a }, 1..3'
> 
> So without the reference to %wids the CV is kept alive because it
> lives in perl's OP-tree and everything is fine.  With the %wids
> reference the sub only lives as long as the Tcl "perlsub" object keeps
> it alive.
> 
> I added some prints to the "perlsub" destructor (FreePerlSub in
> Tcl.xs) and noticed that the sub is freed the first time the callback
> command executes.
> 
> So what happens is that the button store the "perlsub" object just
> fine, but when the object is passed to Tcl_EvalObjEx() in
> TkInvokeButton() the first time then the object is mutated into a
> ByteCodeObj and at this point the CV reference is dropped.  Too bad.

I beleive there could be some sort of optimization when some things are done
at first invoke, and never done if subroutine never called...
But this is irrelevant in our case, I beleive.

> 
> Perhaps there is no hope for getting rid of %anon_refs and the current
> CV leakage.

I think current situation with CVs destroying too early isn't wrong: you
didn't marked CV as used by Tcl interpreter, so Perl frees it as CV goes out
of scope. 
But, as long as sub *is* needed in Tcl, it should be referenced somehow.

I see two ways of doing things:
 - use "trace add command /name/ delete ..." as a proper place to decrement
refcount; (or delete from %anon_refs);
 - keep Tcl-interpreter-wise %anon_refs, and delete all references from it
when interpreter is destroyed.

Second way a bit easier to implement, but first one make things more
precise.

It is makes sence to understand (by code exmaples) why we really need
"precise" refcounting; do you have trouble with leakage in some
applications? or is it an effort to increase module quality (which is a good
thing)?


Also, do I understand correctly that only CVs are within this behaviour, all
other refs are different?

Best regards,
Vadim.

Reply via email to