---
# System prepended metadata

title: Shallow Copy vs. Deep Copy
tags: [42-C++]

---

The concept of "deep copy" refers to creating a new copy of an object where not only the object itself is copied, but also the objects that it contains or points to. A deep copy creates a completely independent duplicate of the original object, including all the data structures or objects that the original object references.

To better understand this, let's break it down:

### 1. **Shallow Copy vs. Deep Copy**
   - **Shallow Copy**: A shallow copy duplicates the top-level structure of an object but does **not** duplicate the objects or data that the original object points to. Instead, it just copies the references (or memory addresses) to those objects. So, both the original and the copy share references to the same underlying objects. Changes made to one object's referenced data will be reflected in the other.
   
   - **Deep Copy**: A deep copy creates a completely independent copy of the object and everything it references. Each object is recursively copied so that the new copy does not share any references with the original. The original and the copied object will not be affected by changes made to each other's contents.

### 2. **Example:**
Imagine you have a class `A` that contains a pointer to an object of class `B`.

```cpp
class B {
public:
    int value;
    B(int val) : value(val) {}
};

class A {
public:
    B* b;
    A(int val) : b(new B(val)) {}

    // Copy constructor (shallow copy)
    A(const A& other) {
        this->b = other.b;  // This only copies the pointer, not the object
    }
    
    // Deep copy constructor
    A(const A& other) {
        this->b = new B(*(other.b));  // This copies the object that b points to
    }
};
```

#### Shallow Copy:
If you create a shallow copy of `A`, both the original and the copy will point to the same `B` object in memory. Any change made to `b->value` in one will be reflected in the other.

```cpp
A a1(10);
A a2 = a1;  // Shallow copy
a2.b->value = 20;

std::cout << a1.b->value;  // Output: 20 (because a1 and a2 share the same B object)
```

#### Deep Copy:
If you create a deep copy of `A`, the `b` pointer in the copied object will point to a new `B` object that is a copy of the original `B`. Changes made to one object will not affect the other.

```cpp
A a1(10);
A a2 = a1;  // Deep copy
a2.b->value = 20;

std::cout << a1.b->value;  // Output: 10 (a1 and a2 now point to different B objects)
std::cout << a2.b->value;  // Output: 20 (a2's B object's value is changed)
```

### 3. **Why is Deep Copy Important?**
Deep copying is necessary when an object contains dynamic memory (like pointers) or objects that should not be shared between different instances of a class. If a shallow copy is made, changes in one object could unintentionally affect another, which could lead to bugs, especially when one of the objects is modified, deleted, or goes out of scope.

Deep copying ensures that:
- Each object has its own independent copy of the data it contains.
- Memory management issues are avoided (e.g., deleting a pointer in one object won't accidentally delete data used by another object).

### 4. **When Should You Use Deep Copy?**
You should use deep copy when:
- Your object owns dynamic memory (i.e., allocated with `new`).
- You want to ensure that changes in one object don’t affect others.
- You’re implementing copy constructors, assignment operators, or functions that modify objects.

### 5. **How is Deep Copy Achieved?**
A deep copy typically involves:
1. **Memory allocation**: Allocate new memory for the nested objects that are part of the object.
2. **Copying**: Copy the contents of the nested objects from the original object to the new ones.

In C++, you typically implement a deep copy using a copy constructor or assignment operator. For example:

```cpp
class A {
public:
    B* b;
    
    A(const A& other) {
        this->b = new B(*(other.b));  // Deep copy: allocate new memory and copy data
    }

    A& operator=(const A& other) {
        if (this != &other) {
            delete b;  // Clean up old memory
            b = new B(*(other.b));  // Deep copy
        }
        return *this;
    }
};
```

In summary, **deep copy** ensures that you have a fully independent copy of an object and its contents, and it's crucial for preventing unintended side effects when dealing with dynamic memory or pointers.



---
## [CH]

"深層複製" 的概念是指創建一個對象的副本，不僅僅是複製對象本身，還會複製該對象所包含或指向的所有對象。深層複製會創建一個完全獨立的原始對象副本，包括原始對象所引用的所有資料結構或對象。

為了更好地理解這一點，讓我們詳細分解：

### 1. **淺層複製與深層複製**
   - **淺層複製**：淺層複製會複製對象的最上層結構，但**不會**複製對象所指向的其他對象或資料。它只會複製對這些對象的引用（或內存地址）。因此，原始對象和複製的對象共享對底層對象的引用。對其中一個對象所引用的資料進行更改，會影響到另一個對象。
   
   - **深層複製**：深層複製會創建一個完全獨立的對象副本，並且會遞歸地複製所有它所引用的對象。每個對象都被複製，使得新副本與原始對象之間沒有共享的引用。原始對象和複製對象不會互相影響，並且對任何一方的變更不會影響另一方。

### 2. **範例：**
假設有一個 `A` 類別，它包含一個指向 `B` 類別對象的指標。

```cpp
class B {
public:
    int value;
    B(int val) : value(val) {}
};

class A {
public:
    B* b;
    A(int val) : b(new B(val)) {}

    // 複製構造函數（淺層複製）
    A(const A& other) {
        this->b = other.b;  // 這只是複製指標，而不是對象
    }
    
    // 深層複製構造函數
    A(const A& other) {
        this->b = new B(*(other.b));  // 這會複製 b 所指向的對象
    }
};
```

#### 淺層複製：
如果你對 `A` 進行淺層複製，那麼原始對象和複製的對象將會指向相同的 `B` 對象。對其中一個對象的 `b->value` 進行更改，會在另一個對象中反映出來。

```cpp
A a1(10);
A a2 = a1;  // 淺層複製
a2.b->value = 20;

std::cout << a1.b->value;  // 輸出：20（因為 a1 和 a2 共享同一個 B 對象）
```

#### 深層複製：
如果你對 `A` 進行深層複製，那麼 `b` 指標在複製對象中會指向一個新的 `B` 對象，這個對象是原始 `B` 對象的副本。對其中一個對象的修改不會影響另一個對象。

```cpp
A a1(10);
A a2 = a1;  // 深層複製
a2.b->value = 20;

std::cout << a1.b->value;  // 輸出：10（a1 和 a2 現在指向不同的 B 對象）
std::cout << a2.b->value;  // 輸出：20（a2 的 B 對象的值被修改）
```

### 3. **為什麼需要深層複製？**
當一個對象包含動態內存（例如通過 `new` 分配的內存）或不應該在多個對象之間共享的對象時，深層複製是必須的。如果進行淺層複製，對其中一個對象的修改可能會無意中影響到另一個對象，這可能會導致錯誤，尤其是當其中一個對象被修改、刪除或超出範圍時。

深層複製能夠確保：
- 每個對象擁有其包含的數據的獨立副本。
- 避免內存管理問題（例如，在一個對象中刪除指標不會意外刪除另一個對象使用的數據）。

### 4. **何時應該使用深層複製？**
當你遇到以下情況時，應該使用深層複製：
- 你的對象擁有動態內存（即使用 `new` 分配的內存）。
- 你希望確保對一個對象的變更不會影響到其他對象。
- 你在實現複製構造函數、賦值操作符或會修改對象的函數時。

### 5. **如何實現深層複製？**
深層複製通常涉及以下步驟：
1. **內存分配**：為對象所包含的嵌套對象分配新的內存。
2. **複製**：將原始對象中嵌套對象的數據複製到新的對象中。

在 C++ 中，你通常會通過複製構造函數或賦值操作符來實現深層複製。例如：

```cpp
class A {
public:
    B* b;
    
    A(const A& other) {
        this->b = new B(*(other.b));  // 深層複製：分配新的內存並複製數據
    }

    A& operator=(const A& other) {
        if (this != &other) {
            delete b;  // 釋放舊的內存
            b = new B(*(other.b));  // 深層複製
        }
        return *this;
    }
};
```

總結來說，**深層複製**確保你擁有一個完全獨立的對象副本及其內容，對於處理動態內存或指標的情況來說，它是至關重要的，因為它可以防止意外的副作用，確保對象之間的變更不會互相影響。


---

# Summary Table

### English Summary Table: Shallow Copy vs. Deep Copy

| **Aspect**               | **Shallow Copy**                                           | **Deep Copy**                                               |
|--------------------------|------------------------------------------------------------|-------------------------------------------------------------|
| **Definition**            | Copies the object, but not the objects it refers to.       | Copies the object and all objects it refers to recursively.  |
| **Memory Allocation**     | Does not allocate new memory for referenced objects.      | Allocates new memory for referenced objects.                |
| **Object References**     | References the same objects as the original.               | References new objects (independent of the original).        |
| **Impact on Original**    | Modifications to referenced objects affect the original.  | Modifications to copied objects do not affect the original.  |
| **Efficiency**            | Faster (less memory usage and less computation).           | Slower (due to memory allocation and copying).               |
| **Use Case**              | Suitable when objects are immutable or shared.             | Suitable when independent objects are needed.                |
| **Example**               | Copying a list of references to the same objects.          | Copying a list of independent objects (e.g., creating a new list with new elements). |
| **Risk of Issues**        | High risk of unintended side-effects due to shared references. | Low risk, as the copied objects are independent.             |

---

### Traditional Chinese Summary Table: Shallow Copy vs. Deep Copy

| **屬性**                  | **淺層複製**                                              | **深層複製**                                               |
|--------------------------|------------------------------------------------------------|-------------------------------------------------------------|
| **定義**                  | 複製對象，但不會複製對象所參考的其他對象。               | 複製對象及其所有參考的對象，包含其內部結構。              |
| **記憶體分配**            | 不會為所參考的對象分配新記憶體。                          | 為所參考的對象分配新記憶體。                                |
| **對象參考**              | 與原始對象共享相同的引用對象。                            | 與原始對象無關聯，引用新創建的獨立對象。                   |
| **對原始對象的影響**      | 修改引用的對象會影響原始對象。                            | 修改複製對象不會影響原始對象。                              |
| **效率**                  | 較快（因為使用較少的記憶體和計算量）。                    | 較慢（因為需要記憶體分配和複製過程）。                      |
| **使用情境**              | 當對象是不可變的或需要共享時，適用淺層複製。             | 當需要獨立對象時，適用深層複製。                           |
| **範例**                  | 複製一個引用同一對象的列表。                              | 複製一個具有獨立元素的新列表。                              |
| **潛在問題風險**          | 由於共享引用，容易產生不預期的副作用。                    | 風險較低，因為複製的對象相互獨立。                          |



---

## More Summary

### Shallow Copy:
- **Shallow Copy** copies the *pointer* (or reference) to the object, not the object itself.
- This means the new object (or copy) will point to the same memory location as the original. So, both the original and the copied object will refer to the same internal data or resources.
- If one object changes the data it points to, the other will also be affected, because both are pointing to the same memory.

### Deep Copy:
- **Deep Copy** creates a new object and also recursively copies all the objects the original object references.
- This means a deep copy involves allocating new memory for all the objects involved, so the new object and the original object are completely independent. Changes in the copied object will not affect the original object and vice versa.
  
### Simplified View:
- **Shallow Copy** = Copy the **pointer/reference** (just copies the address).
- **Deep Copy** = Copy the **entire object** and all objects it refers to (actually creates new instances and copies the data).

In summary:
- **Shallow Copy** = Copy the *pointer* (reference) to the object.
- **Deep Copy** = Copy the *entire object* and everything it points to.

### 簡單理解：

- **淺層複製** 只複製物件的 **指標（或引用）**，而不是物件本身。
- 這意味著新複製的物件將指向與原始物件相同的記憶體位置。也就是說，原始物件和複製的物件會指向相同的內部資料或資源。
- 如果其中一個物件修改了它指向的資料，另一個物件也會受到影響，因為兩者指向的是相同的記憶體位置。

### 深層複製：
- **深層複製** 則會建立一個新物件，並遞歸地複製原始物件所參考的所有物件。
- 這意味著深層複製不僅複製物件本身，還會為原始物件參考的每個物件分配新記憶體。所以，複製出來的物件和原始物件是完全獨立的，彼此之間不會互相影響。對複製物件的任何更動都不會影響原始物件，反之亦然。

### 簡化解釋：
- **淺層複製** = 複製 **指標/引用**（僅複製記憶體位置）。
- **深層複製** = 複製 **整個物件** 和它所參考的所有物件（實際上會創建新的物件並複製資料）。

### 總結：
- **淺層複製** = 複製 **指標**（或引用）到物件。
- **深層複製** = 複製 **整個物件** 和所有它所參考的物件。