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.