Home >Backend Development >C++ >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:
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:
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:
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!