in reply to Should I use weaken on an object attribute containing a reference to an object which contains reference back to original object?

That are some unfortunate ways to say it.

The purpose of weaken is to assist Perl's garbage collection mechanism. This mechanism returns memory to the pool when there are no more references to it. It is not possible to demonstrate this with just the classes: Let me add some main code. Warning: This code runs forever!

package main; while (1) { my $dir = Practice::Dir->new; my $file = Practice::File->new; $dir->add_file($file); $file->add_dir($dir); }

If you comment out your call to weaken and run the code, then you'll see the memory consumption increase slowly, but steadily.

Explanation: At the end of each iteration, the variables $dir and $file go out of scope. The object behind $dir will not be freed, because it is referenced to by the $file object - and vice versa. If you weaken the dir attribute of the file, then the object behind $dir can be freed, and since this is now gone, the object behind $file can also be freed.

  • Comment on Re: Should I use weaken on an object attribute containing a reference to an object which contains reference back to original object?
  • Download Code