VLSI DV Interview Puzzles · All levels
Dynamic Array Resize with Class Handles
Explain why changing `da[0].v` also changes `db[0].v` after resize-copy.
Puzzle
Difficulty: Hard · Puzzle 4 of 6 · Topic: Queue and Array Puzzles
Explain why changing `da[0].v` also changes `db[0].v` after resize-copy.
Code
systemverilog
class item;
int v;
function new(int v); this.v = v; endfunction
endclass
module p4;
item da[];
item db[];
initial begin
da = new[2];
da[0] = new(10);
da[1] = new(20);
db = new[3](da);
db[2] = new(30);
da[0].v = 99;
$display("da0=%0d db0=%0d db2=%0d", da[0].v, db[0].v, db[2].v);
end
endmoduleHint
`new[N](old)` copies elements, but if element type is class handle, copied value is the handle.
Step-by-step solution
diagram
1) `db = new[3](da)` copies first two elements from `da` into `db`.
2) Those elements are class handles, so db[0] and da[0] reference the same object.
3) Updating `da[0].v` updates that shared object, visible through `db[0].v`.
4) `db[2]` is independently constructed and remains 30.Answer
Answer: da0=99, db0=99, db2=30
Why candidates get it wrong
Candidates conflate array copy (by value) with deep copy of objects stored in the array.
Interviewer follow-up
What code pattern gives deep-copy semantics for arrays of class handles?