Deep Copy vs Shallow Copy in C++

·

In C++, copying objects can be done in two ways: deep copy and shallow copy. A shallow copy duplicates the object’s immediate values. If the object contains pointers, only the pointers are copied, not the actual data. This can lead to issues like dangling pointers. In contrast, a deep copy creates a complete duplicate of the object and its data.

Consider this example:
“`cpp
#include
#include
using namespace std;
class Shallow {
public:
int* data;
Shallow(int value) { data = new int(value); }
~Shallow() { delete data; }
};
int main() {
Shallow obj1(10);
Shallow obj2 = obj1; // Shallow copy
cout << *obj2.data; // Accesses same memory return 0; } ``` In this code, obj2 is a shallow copy of obj1. Both point to the same memory. This can cause problems if one object is modified or deleted. To implement a deep copy, you need to define a copy constructor. This ensures all data is duplicated correctly and safely. Choosing between deep and shallow copies depends on your use case. For objects managing dynamic memory, deep copies are often safer.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *