SystemVerilog OOP Mastery · All levels

Shallow vs Deep Copy: Exercises

Exercises for Shallow vs Deep Copy.

Practice exercises

Exercise 1

You have class packet with field header h. Write copy logic so packet b becomes independent from packet a, including header.

Solution

diagram
Allocate or clone header explicitly in copy: if (a.h == null) b.h = null; else begin if (b.h == null) b.h = new; b.h.id = a.h.id; end. Do not assign b.h = a.h.

Exercise 2

A scoreboard stores transactions in a queue and later sees earlier entries change. What is the first fix to apply?

Solution

diagram
Store clones, not original handles. Replace q.push_back(tr) with q.push_back(tr.clone()) where clone performs deep copy of nested handles.

Related topics