Shallow Copy and Deep Copy in SystemVerilog
Shallow Copy and Deep Copy in SystemVerilog
In SystemVerilog, shallow copy and deep copy are used when copying objects of a class.
The difference lies in how the class properties, especially dynamic and object handles,
are copied.
1. Shallow Copy
A shallow copy only copies the object handle (reference), meaning that both the original
and copied objects point to the same memory. Any modifications to one object will reflect
in the other.
module shallow_copy_test;
A obj1, obj2;
initial begin
obj1 = new(10);
obj2 = obj1; // Shallow copy: both obj1 and obj2 point to the same memory
Output:
Before modification: obj1.data = 10, obj2.data = 10
After modification: obj1.data = 20, obj2.data = 20
Since obj1 and obj2 are referencing the same memory, modifying obj2.data changes
obj1.data as well.
2. Deep Copy
A deep copy creates a completely new object with its own memory space. Changes in the
copied object do not affect the original.
module deep_copy_test;
A obj1, obj2;
initial begin
obj1 = new(10);
obj2 = obj1.copy(); // Deep copy: obj2 is a separate object
Output:
Before modification: obj1.data = 10, obj2.data = 10
After modification: obj1.data = 10, obj2.data = 20
Since obj2 is a newly created object with its own memory, modifying obj2.data does not
change obj1.data.
Shallow vs. Deep Copy for Class Containing Dynamic Arrays
If a class has dynamic arrays, shallow copying will cause both objects to share the same
array, while deep copying will create a new array.
function new();
data = new[3]; // Dynamic array allocation
data = '{1, 2, 3};
endfunction
module test;
A obj1, obj2;
initial begin
obj1 = new();
obj2 = obj1.copy(); // Deep copy
Since copy() allocated a new dynamic array, modifying obj2.data does not affect
obj1.data.
Summary
• For classes with dynamic arrays or other objects, always use deep copy to avoid
unintended modifications.