In C++, a deep copy is a type of copy that creates a new object and copies all the data from the original object into the new object, including any data that is pointed to by the original object's pointers.
When you make a deep copy of an object, you create a new object with its own memory space, independent of the original object. This means that any changes made to the original object will not affect the new object, and vice versa.
A deep copy is often used when working with objects that have dynamically allocated memory, such as objects created on the heap using the new
operator. In this case, a simple copy of the object using the default copy constructor or assignment operator would result in both objects pointing to the same memory location, which can cause problems if one object is modified.
Here is an example of a deep copy:
class Person { public: Person(string name, int age); Person(const Person& other); // Copy constructor ~Person(); void introduce(); private: string name; int age; int* id; // Pointer to dynamically allocated memory }; Person::Person(string name, int age) { this->name = name; this->age = age; this->id = new int(12345); // Allocate memory for id } Person::Person(const Person& other) { this->name = other.name; this->age = other.age; this->id = new int(*other.id); // Allocate new memory for id and copy data } Person::~Person() { delete id; // Deallocate memory for id } void Person::introduce() { cout << "Hi, my name is " << name << " and I am " << age << " years old. My ID is " << *id << "." << endl; } int main() { Person p1("Alice", 25); Person p2 = p1; // Use copy constructor to create new object p2 p1.introduce(); p2.introduce(); // Change ID of p1 *p1.id = 54321; p1.introduce(); p2.introduce(); return 0; }
In this example, the Person
class has a pointer to a dynamically allocated integer id
. The copy constructor for the Person
class creates a new id
for the copied object, and copies the data from the original id
into the new id
. The destructor for the Person
class deallocates the id
memory when the object is destroyed.
In the main
function, p1
and p2
are created using the default constructor and the copy constructor, respectively. Both objects are introduced using the introduce
function, and the output shows that they have the same name, age, and ID.
Then, the id
of p1
is changed to 54321. This change does not affect p2
, because the two objects have separate memory spaces for their id
s.
Overall, deep copying is an important technique for working with objects that have dynamically allocated memory, and can help avoid bugs and memory leaks in C++ programs.