Wednesday, May 1, 2013

shallow copy vs deep copy


Packet p1;
Packet p2;
p1 = new;
p2 = new p1;//shallow copy
The last statement has new executing a second time, thus creating a new object p2, whose class properties
are copied from p1. This is known as a shallow copy. All of the variables are copied across integers, strings,
instance handles, etc. Objects, however, are not copied, only their handles; as before, two names for the
same object have been created. This is true even if the class declaration includes the instantiation operator
new.
It shall be illegal to use a typed constructor call for a shallow copy (see 8.8).
A shallow copy executes in the following manner:

1) An object of the class type being copied is allocated. This allocation shall not call the object’s constructor
or execute any variable declaration initialization assignments.
2) All class properties, including the internal states used for randomization and coverage, are copied to
the new object. Object handles are copied; this includes the object handles for covergroup objects
(see Clause 19). An exception is made for embedded covergroups (see 19.4). The object handle of
an embedded covergroup shall be set to null in the new object. The internal states for randomization
include the random number generator (RNG) state, the constraint_mode status of constraints, the
rand_mode status of random variables, and the cyclic state of randc variables (see Clause 18).
3) A handle to the newly created object is assigned to the variable on the left-hand side.
NOTE—A shallow copy does not create new coverage objects (covergroup instances). As a result, the properties of the new object are not covered.

Several things are noteworthy. First, class properties and instantiated objects can be initialized directly in a
class declaration. Second, the shallow copy does not copy objects. Third, instance qualifications can be
chained as needed to reach into objects or to reach through objects:
b1.a.j // reaches into a, which is a property of b1
p.next.next.next.val // chain through a sequence of handles to get to val
To do a full (deep) copy, where everything (including nested objects) is copied, custom code is typically
needed. For example:
Packet p1 = new;

Packet p2 = new;
p2.copy(p1);
where copy(Packet p) is a custom method written to copy the object specified as its argument into its
instance.