Chun Lin
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    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. ### 簡單理解: - **淺層複製** 只複製物件的 **指標(或引用)**,而不是物件本身。 - 這意味著新複製的物件將指向與原始物件相同的記憶體位置。也就是說,原始物件和複製的物件會指向相同的內部資料或資源。 - 如果其中一個物件修改了它指向的資料,另一個物件也會受到影響,因為兩者指向的是相同的記憶體位置。 ### 深層複製: - **深層複製** 則會建立一個新物件,並遞歸地複製原始物件所參考的所有物件。 - 這意味著深層複製不僅複製物件本身,還會為原始物件參考的每個物件分配新記憶體。所以,複製出來的物件和原始物件是完全獨立的,彼此之間不會互相影響。對複製物件的任何更動都不會影響原始物件,反之亦然。 ### 簡化解釋: - **淺層複製** = 複製 **指標/引用**(僅複製記憶體位置)。 - **深層複製** = 複製 **整個物件** 和它所參考的所有物件(實際上會創建新的物件並複製資料)。 ### 總結: - **淺層複製** = 複製 **指標**(或引用)到物件。 - **深層複製** = 複製 **整個物件** 和所有它所參考的物件。

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Google Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully