Shallow Copy vs Deep Copy

Seungyun Lee·2026년 4월 20일

Interview

목록 보기
5/5

1. Shallow Copy vs Deep Copy의 본질적 차이

A. Shallow Copy (얕은 복사)

개념: 시스템 베릴로그에서 객체는 항상 핸들(Handle, 포인터와 유사) 형태로 존재합니다. 얕은 복사는 객체 내부의 알맹이가 아니라, 이 핸들의 주소값만 복사하는 것을 의미합니다.

치명적 결과: 원본 객체와 복사된 객체가 메모리 상의 동일한 하위 객체(Nested object)를 가리키게 됩니다. 만약 복사본에서 내부 배열의 값을 수정하면, 원본의 값도 동시에 변해버립니다. 검증 환경에서는 패킷 데이터가 오염되는 치명적인 버그로 이어집니다.

B. Deep Copy (깊은 복사)

개념: 핸들만 복사하는 것이 아니라, 객체가 내부에 품고 있는 모든 하위 객체들에 대해 새로운 메모리를 할당(new())하고 내부의 데이터 값을 일일이 옮겨 적는 방식입니다.

안전성: 복사가 완료되면 원본과 복사본은 메모리 상에서 완벽하게 분리되어 독립적으로 동작합니다. 어느 한쪽을 수정해도 다른 쪽에 영향을 주지 않습니다.

2. 제공된 코드의 완벽한 분해 (Code Breakdown)

보여주신 코드는 하위 객체(Item)를 배열 형태로 가지고 있는 상위 객체(Container)를 완벽하게 Deep Copy하는 정석적인 패턴입니다

class Item;
  int value;

  // Method to deep copy the basic Item object
  function Item copy();
    copy = new();            // 1. Allocate new memory for the cloned Item
    copy.value = this.value; // 2. Copy the actual primitive data
  endfunction
endclass

class Container;
  Item items[]; // Dynamic array of Item handles

  // Method to deep copy the Container and all nested Items
  function Container do_copy();
    do_copy = new(); // 1. Allocate memory for the new Container

    // 2. Allocate memory for the new dynamic array to match the original size
    do_copy.items = new[this.items.size()]; 

    // 3. Iterate through each element to perform Deep Copy
    foreach (this.items[i]) begin
      // CRITICAL POINT: Calling the copy() method of the nested object.
      // If we wrote "do_copy.items[i] = this.items[i];", it would be a Shallow Copy.
      do_copy.items[i] = this.items[i].copy(); 
    end
  endfunction
endclass
profile
Design Verification engineer

0개의 댓글