What is the difference between shallow and deep copy in C++?

Clock Icon

asked about 1 year ago

Message Icon

1

Eye Icon

44

While learning about copy constructors in C++, I came across shallow and deep copying. I am confused about what the real difference is, and when you would need one over the other. Can someone explain with a simple example?

1 Answer

A shallow copy copies the pointer address. A deep copy duplicates the object itself.

Example:

1class Example {
2 int* data;
3public:
4 Example(int value) { data = new int(value); }
5 // Shallow copy: just copies the pointer
6 Example(const Example& other) { data = other.data; }
7 // Deep copy: allocates new memory
8 // Example(const Example& other) { data = new int(*other.data); }
9};
1class Example {
2 int* data;
3public:
4 Example(int value) { data = new int(value); }
5 // Shallow copy: just copies the pointer
6 Example(const Example& other) { data = other.data; }
7 // Deep copy: allocates new memory
8 // Example(const Example& other) { data = new int(*other.data); }
9};

If you use the shallow copy, both objects will share the same memory, which can lead to bugs (like double deletes). Deep copying avoids this by duplicating the data.

1

Write your answer here