☰ Categories

Deep Copy Functionality

a Programming Expert. You are highly skilled in software development, specializing in data structure manipulation and memory management.

CategoryDevelopment › Coding
TagsDraftingAnalyzingDeveloperCode
Prompt
Act as a Programming Expert. You are highly skilled in software development, specializing in data structure manipulation and memory management. Your task is to instruct users on how to implement deep copy functionality in their code to ensure objects are duplicated without shared references.

You will:
- Explain the difference between shallow and deep copies.
- Provide examples in popular programming languages like Python, Java, and JavaScript.
- Highlight common pitfalls and how to avoid them.

Rules:
- Use clear and concise language.
- Include code snippets for clarity.

What this prompt does

This programming explainer helps users learn deep copy implementation to avoid shared object references. It asks for examples in Python, Java, and JavaScript.

Model comparison

ChatGPT offers the best balance of accuracy and concision. Gemini is detailed but contains a code flaw, while [C] is missing.

ChatGPTTop overall
49/ 50

+ Accurately covers implementations and pitfalls in all three languages.

- Thorough, but slightly longer than necessary for the task.

Gemini
44/ 50

+ Specifically addresses cycles and custom copy implementations.

- Python memo registration occurs too late to handle self-cycles.

CriterionChatGPTGeminiLeader
Instruction following1010Tie
Accuracy107ChatGPT +43%
Specificity1010Tie
Structure109ChatGPT +11%
Right length98ChatGPT +13%

Scored 1–10 by gpt-5.6-sol with model names hidden (2026-09-25). This is an AI review, not a measurement.

Read full answers

We gave three models the same input and copied their answers unedited. Each ran in its CLI (an agent harness), and answers in the ChatGPT or Claude apps or on the web may differ. Outputs are in Korean.

gpt-5.6-luna (codex CLI · 에이전트 하네스) · Run on 2026-09-24

얕은 복사와 깊은 복사

  • 얕은 복사(Shallow Copy): 최상위 객체만 복사하고, 내부 객체는 원본과 공유합니다.
  • 깊은 복사(Deep Copy): 내부에 포함된 객체까지 재귀적으로 복사하여 원본과 완전히 분리합니다.
원본 ──> 내부 객체
복사본 ──> 같은 내부 객체       // 얕은 복사

원본 ──> 내부 객체 A
복사본 ──> 별도의 내부 객체 B     // 깊은 복사

Python

얕은 복사

original = [[1, 2], [3, 4]]
copied = original.copy()

copied[0].append(5)

print(original)  # [[1, 2, 5], [3, 4]]

내부 리스트가 공유되므로 원본도 변경됩니다.

깊은 복사

import copy

original = [[1, 2], [3, 4]]
copied = copy.deepcopy(original)

copied[0].append(5)

print(original)  # [[1, 2], [3, 4]]
print(copied)    # [[1, 2, 5], [3, 4]]

copy.deepcopy()는 중첩된 리스트와 객체까지 복사합니다.

Java

Java의 clone()은 기본적으로 얕은 복사이므로, 깊은 복사를 직접 구현하는 것이 안전합니다.

class Address {
    String city;

    Address(String city) {
        this.city = city;
    }

    Address(Address other) {
        this.city = other.city;
    }
}

class Person {
    String name;
    Address address;

    Person(String name, Address address) {
        this.name = name;
        this.address = address;
    }

    // 복사 생성자
    Person(Person other) {
        this.name = other.name;
        this.address = new Address(other.address);
    }
}

사용 예:

Person original = new Person(
    "Kim",
    new Address("Seoul")
);

Person copied = new Person(original);
copied.address.city = "Busan";

System.out.println(original.address.city); // Seoul
System.out.println(copied.address.city);   // Busan

String, Integer처럼 불변(immutable) 객체는 참조를 공유해도 안전한 경우가 많습니다. 반면 List, 배열, 사용자 정의 가변 객체는 직접 복사해야 합니다.

List<String> copied = new ArrayList<>(originalList);

단, 리스트 내부에 또 다른 가변 객체가 있다면 해당 요소까지 별도로 복사해야 합니다.

JavaScript

얕은 복사

const original = {
  name: "Kim",
  address: {
    city: "Seoul"
  }
};

const copied = { ...original };

copied.address.city = "Busan";

console.log(original.address.city); // Busan

스프레드 문법은 최상위 속성만 복사합니다.

깊은 복사: structuredClone

const original = {
  name: "Kim",
  address: {
    city: "Seoul"
  }
};

const copied = structuredClone(original);

copied.address.city = "Busan";

console.log(original.address.city); // Seoul

structuredClone()은 중첩 객체, 배열, 순환 참조 등을 처리할 수 있어 일반적으로 권장됩니다.

JSON 방식의 한계

const copied = JSON.parse(JSON.stringify(original));

간단한 데이터에는 사용할 수 있지만 다음 값이 손실되거나 변형될 수 있습니다.

  • Date
  • Map, Set
  • undefined
  • 함수
  • Symbol
  • 순환 참조

따라서 가능하면 structuredClone()을 사용하는 것이 좋습니다.

주요 주의사항

  1. 중첩된 가변 객체를 확인하세요.
    최상위 객체만 복사하면 내부 배열이나 객체는 공유될 수 있습니다.

  2. 불변 객체와 가변 객체를 구분하세요.
    불변 객체는 공유해도 안전하지만, 가변 객체는 별도 복사가 필요합니다.

  3. 순환 참조를 고려하세요.
    객체가 자기 자신을 참조하면 단순한 재귀 복사는 무한 루프를 일으킬 수 있습니다.

  4. 깊은 복사의 비용을 고려하세요.
    객체가 크거나 복잡하면 메모리와 실행 시간이 많이 필요합니다.

  5. 복사 대상에서 제외할 값을 확인하세요.
    파일 핸들, 데이터베이스 연결, 네트워크 소켓 같은 리소스는 단순 복사로 정상적으로 복제되지 않습니다.

핵심은 복사 후 내부 객체를 변경했을 때 원본이 영향을 받는지 확인하는 것입니다. 영향을 받지 않아야 한다면 깊은 복사가 필요합니다.

More in this category

12-Month AI and Computer Vision Roadmap for Defense Applications
2046 Puzzle Game Challenge
21st.dev component prompt
3D FACTORY
3D FPS Game