in reply to DESTROYing an object

well, is there any way to force an object to be garbage-collected? or, to be more precise, is there any way to make a Tk::Photo or Tk::Image object free the memory it's using to store its image?

Replies are listed 'Best First'.
Re: Re: DESTROYing an object
by gmpassos (Priest) on Dec 12, 2002 at 04:50 UTC
    You can't "force", because this only happens when you don't need any more the object! In other words, the garbage-collect only happens when the variable that holds the object goes out! To do that just rewrite the variable:
    undef $obj ; ## or: $obj = undef ; ## or: $obj = 123 ;
    But if you have another variable with the same content of $obj the garbage-collect doesn't happens!

    Some tests for DESTROY:

    ## This is for the main package, never do that! package main ; sub new { bless( {} , 'main') ;} sub hy { print "HELLO!\n" ;} sub DESTROY { print "DESTROY!\n" ;} my $obj = main->new ; # create the object. my $clone = $obj ; # save it in the clone. Comment this line # to see that the undef $obj works! print ">>$obj\n" ; # print the references. print ">>$clone\n" ; $obj->hy ; # test a method. undef $obj ; # lose the object. print "__END__\n" ; # End point! If you really lose # the object the DESTROY is called # before this print! Test to comment $clone.
    You asked for a way to free the memory used to hold the images. Don't forget that Perl, and generally any process in most OS, don't return the memory that it uses to the OS! Perl when clean the memory, it just clean it to be reused for new variables in the same process.

    Graciliano M. P.
    "The creativity is the expression of the liberty".

Re: Re: DESTROYing an object
by TGI (Parson) on Dec 12, 2002 at 05:13 UTC

    You have to have all references to the object go out of scope. You can help this along by undefing the object reference.

    Perl's garbage collection system uses reference counts--so when nothing points to a piece of data, it can be garbage collected. Note that I said can. AFAIK, there is no way to force the issue.

    Check out this note in the perlobj document. Scroll up a bit to read the section on destructors. You might find it interesting, too.


    TGI says moo

      No need to force it. As soon as the count goes to 0, Perl attempts to get rid of it. This is immediate destruction with 3 exceptions that I know of. Those exceptions are bugs, cases where counts are not tabulated immediately (happens with map) and global destruction at the end of your program.