Home  >  Article  >  Backend Development  >  Deep Copy vs. Shallow Copy: When Do I Need a True Copy of My Data?

Deep Copy vs. Shallow Copy: When Do I Need a True Copy of My Data?

Barbara Streisand
Barbara StreisandOriginal
2024-10-27 11:01:30833browse

 Deep Copy vs. Shallow Copy: When Do I Need a True Copy of My Data?

Deep Copy vs. Shallow Copy

Question:

What are the key differences between deep copy and shallow copy?

Answer:

Shallow Copy:

  • Copies the object's values but retains references to shared objects.
  • Example:

    <code class="c++">class X {
    private:
      int i;
      int *pi;
    public:
      X() : pi(new int) {}
      X(const X& copy) : i(copy.i), pi(copy.pi) {}
    };</code>

    In this shallow copy, pi references the same int object in both the original and copied objects.

Deep Copy:

  • Creates a complete copy of the original object, including all embedded objects.
  • Example:

    <code class="c++">class X {
    private:
      int i;
      int *pi;
    public:
      X() : pi(new int) {}
      X(const X& copy) : i(copy.i), pi(new int(*copy.pi)) {}
    };</code>

    In this deep copy, pi points to a new int object with the same value as the original.

Copy Constructor Type:

The default copy constructor depends on the behavior of each member's copy constructor:

  • For scalar types, the default assignment operator is used, resulting in a shallow copy.
  • However, it is not strictly correct to say that the default copy constructor always performs a shallow copy. It could implement a deep copy, or even a combination of deep and shallow copying, depending on the member types' copy behaviors.

Example:

In the following example, the default copy constructor creates a deep copy for the std::vector member due to its implementation:

<code class="c++">class Y {
private:
    std::vector<int> v;
public:
    Y() {}
    Y(const Y& copy) : v(copy.v) {}
};</code>

In this case, the std::vector's copy constructor creates a deep copy of its contents.

The above is the detailed content of Deep Copy vs. Shallow Copy: When Do I Need a True Copy of My Data?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn