Shallow vs Deep Copy of Class Objects
When you copy a class object you must know whether you are copying the handle or the data. Getting this wrong is one of the most common SystemVerilog bugs: two variables end up pointing at the same object, and a change through one silently corrupts the other.
Assignment, shallow copy, deep copy
Plain assignment (b = a) copies only the handle — both now reference the same object. The built-in new (a) does a shallow copy: a fresh object, but nested object handles are still shared. A deep copy is one you write, allocating new nested objects so the two are fully independent.
module tb;
class Inner; int x; endclass
class Outer;
int tag;
Inner in;
function new(); in = new(); endfunction
function Outer deep(); // explicit deep copy
deep = new();
deep.tag = tag;
deep.in = new(); deep.in.x = in.x; // allocate a fresh Inner
endfunction
endclass
initial begin
Outer a = new();
Outer alias_h, dp;
a.tag = 1; a.in.x = 100;
alias_h = a; // handle copy: SAME object
dp = a.deep(); // deep copy: independent
a.in.x = 999; // mutate the original's nested obj
$display("handle-alias sees %0d (shared!) deep sees %0d (safe)", alias_h.in.x, dp.in.x);
$finish;
end
endmodulehandle-alias sees 999 (shared!) deep sees 100 (safe) - /var/folders/l0/gs5hnkm56g54bmxg32r6nnwr0000gn/T/tmp2jvs3clw/tb.sv:22: Verilog $finish
The built-in shallow copy sits between these two — Outer sh = new a; makes a fresh top-level object but still shares the nested in handle, so sh.in.x would also read 999. Only the hand-written deep copy is fully independent.
Check yourself
What does <code>b = a</code> do when a and b are class handles?
It copies the handle only. Both b and a refer to the same single object; there is no new object, and a change through either is visible through the other.
Why doesn’t the built-in shallow copy <code>new(a)</code> fully duplicate an object with nested objects?
Shallow copy creates a new top-level object but copies nested handles by reference, so the copy and original share the same nested sub-objects. Independent copies of nested objects require a hand-written deep copy (or UVM’s do_copy).
Share your question in comments or talk to our mentor team for batch guidance.
Compile and simulate this in the browser — no install. Edit the code and re-run instantly.
Learn Verilog with mentors, labs and placement support
This free series is maintained by the ChipXpert training team in Hyderabad & Bengaluru. Go deeper with instructor-led courses on real EDA tools.
Explore VLSI Courses