A shared class consists of a pointer to a shared data block that
contains a reference count and the data.
When a shared object is created, it sets the reference count to 1. The
reference count is incremented whenever a new object references the shared
data, and decremented when the object dereferences the shared data. The
shared data is deleted when the reference count becomes zero.
When dealing with shared objects, there are two ways of copying an object.
We usually speak about deep and shallow copies. A deep copy implies
duplicating an object. A shallow copy is a reference copy, i.e. just a
pointer to a shared data block. Making a deep copy can be expensive in
terms of memory and CPU. Making a shallow copy is very fast, because it
only involves setting a pointer and incrementing the reference count.
Object assignment (with operator=()) for implicitly and explicitly shared
objects is implemented using shallow copies. A deep copy can be made by
calling a copy() function.
The benefit of sharing is that a program does not need to duplicate data
unnecessarily, which results in lower memory use and less copying of data.
Objects can easily be assigned, sent as function arguments, and returned
from functions.
Now comes the distinction between explicit and implicit sharing. Explicit
sharing means that the programmer must be aware of the fact that objects
share common data. Implicit sharing means that the sharing mechanism
takes place behind the scenes and the programmer does not need to worry
about it.
All of the shared classes in Pegasus are explicitly shared. These classes
have a clone() function that returns a deep copy with a reference count of 1.