SystemVerilog OOP Mastery · All levels

Shallow vs Deep Copy: Code Examples

Code Examples for Shallow vs Deep Copy.

Code examples

Handle assignment aliases the same object

systemverilog
class hdr;
  int id;
endclass

class pkt;
  int seq;
  hdr h;
endclass

pkt a = new;
a.seq = 10;
a.h = new;
a.h.id = 99;

pkt b = a;
b.h.id = 123;
// a.h.id is now 123 because a and b alias the same object

The assignment pkt b = a does not duplicate the pkt object. Any write through b is visible through a because both handles point to the same heap object.

new rhs clones top-level, not nested handles

systemverilog
class hdr;
  int id;
endclass

class pkt;
  int seq;
  hdr h;
endclass

pkt src = new;
src.seq = 5;
src.h = new;
src.h.id = 7;

pkt top_copy = new src;
top_copy.seq = 11;
top_copy.h.id = 88;
// src.h.id also becomes 88 because h handle was copied

new src gives a distinct pkt object, so seq is independent, but the nested hdr handle remains shared until you explicitly deep-copy hdr.

Deep copy recursively allocates nested objects

systemverilog
class hdr;
  int id;
  function hdr clone();
    hdr c = new;
    c.id = id;
    return c;
  endfunction
endclass

class pkt;
  int seq;
  hdr h;
  function void deep_copy(pkt rhs);
    seq = rhs.seq;
    if (rhs.h == null) h = null;
    else h = rhs.h.clone();
  endfunction
endclass

The key step is allocating a fresh hdr for destination state instead of reusing rhs.h. That breaks aliasing across object graphs.

Related topics