Home > Backend Development > C++ > body text

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

Barbara Streisand
Release: 2024-10-27 11:01:30
Original
832 people have browsed it

 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>
    Copy after login

    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>
    Copy after login

    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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!