Programming Perl in C
Objects start their lives with a refcount of 1. When a reference to the object is
created, its refcount is incremented. When an object goes out of scope, its refcount
is decremented. Finally, when a reference is removed, the refcount of the object is
decremented. The object is freed when its refcount reaches 0.
Most variables don't get referenced and simply go from having a refcount of
1 to having a refcount 0 when they go out of scope:
{
my $a = "foo"; # $a has a refcount of 1
}
# $a goes out of scope and has its refcount decremented. Since its refcount is
# now 0, the memory used by $a is freed.
Even when references are created they are normally confined to a single scope:
{
my $a = "foo"; # $a has a refcount of 1
my $b = \$a; # $b has a refcount of 1, $a has a refcount of 2
}
# $a and $b go out of scope and have their refcounts decremented. Since $b
# referenced $a, $a has its refcount decremented again. Now both $a and $b
# have refcounts of 0 and their memory is freed.
Things start getting complicated when an object is referenced by a variable
from another scope. Here's a simple example:
my $a; # $a has a refcount of 1
{
my $b = "foo"; # $b has a refcount of 1
$a = \$b; # $a now references $b. $b has a refcount of 2
}
# $b goes out of scope. $b has its refcount decremented and now has a
# refcount of 1. $b is still live since $a has a reference to it.
$a = 10; # $a no longer references $b. $b now has a refcount of 0 and is
# freed by the garbage collector.
19
193
3
footer
Our partners:
PHP: Hypertext Preprocessor Best Web Hosting
Java Web Hosting
Inexpensive Web Hosting
Jsp Web Hosting
Cheapest Web Hosting
Jsp Hosting
Cheap Hosting
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved