views:

56

answers:

1

What exactly are the weak references that KiokuDB tutorial mentions?

How do they differ from 'normal' references?

+6  A: 

A normal reference prevents the thing being referred to from being garbage collected. A weak reference is like a normal reference, but does not prevent garbage collection. When the last normal reference to an entity is removed, it gets garbage collected, and any weak references to it become undef.

This is useful if you have circular references. A reference-count garbage collector (like Perl uses) cannot remove things with circular references, because their reference count never goes to 0.

For example, consider a tree structure, where parent nodes have references to their child nodes, and child nodes have a reference to their parent. By making the child-to-parent references weak, the tree will be automatically garbage collected when there are no external references to it.

In Perl, weak references can be created with the weaken function in Scalar::Util. Moose also allows you to mark attributes as weak_ref.

cjm