Deep Copy in C++ - Definition, Working, Copy Constructor and Examples

In C++, a Deep Copy creates a separate copy of an object, including the dynamically allocated memory owned by that object. Instead of copying only memory addresses, deep copying allocates new memory and copies the actual data into it. Deep copy is especially important when a class contains pointer data members that manage dynamically allocated memory. It ensures that two objects do not unintentionally share the same memory.

C++ में Deep Copy किसी object की एक स्वतंत्र copy बनाता है, जिसमें उस object द्वारा उपयोग की जाने वाली dynamically allocated memory भी अलग से बनाई जाती है। इसमें केवल memory address copy नहीं होता, बल्कि वास्तविक data भी नई memory में copy किया जाता है। Deep Copy विशेष रूप से तब महत्वपूर्ण होता है जब किसी class में ऐसे pointer data members हों जो dynamically allocated memory को manage करते हैं। यह सुनिश्चित करता है कि दो objects अनजाने में एक ही memory को share न करें।

What Is Deep Copy in C++?

A deep copy duplicates the contents of an object and creates independent memory for its dynamically allocated resources. Changes made to one object do not affect the copied object.

Deep Copy किसी object के data की पूरी copy बनाता है और उसके dynamically allocated resources के लिए अलग memory allocate करता है। इसलिए एक object में किए गए changes दूसरे copied object को प्रभावित नहीं करते।

Consider a class containing an integer pointer. When an object is copied using a deep copy, the new object receives a different memory location containing the same initial value.

मान लीजिए किसी class में एक integer pointer है। Deep Copy के माध्यम से object copy करने पर नए object को एक अलग memory location मिलती है, जिसमें शुरुआत में वही value होती है।

Simple Example of Deep Copy in C++

The following example demonstrates how two objects can maintain independent copies of dynamically allocated data.

निम्न उदाहरण दिखाता है कि दो objects dynamically allocated data की स्वतंत्र copies कैसे रख सकते हैं।

#include <iostream>
using namespace std;
class Demo {
private:
int* ptr;
public:
Demo(int value) {
ptr = new int(value);
}
// Deep Copy Constructor
Demo(const Demo& obj) {
ptr = new int(*obj.ptr);
}
// Destructor
~Demo() {
delete ptr;
}
void setValue(int value) {
*ptr = value;
}
void display() const {
cout << "Value: " << *ptr << endl;
}
};
int main() {
Demo obj1(100);
Demo obj2 = obj1;
cout << "Original Object: ";
obj1.display();
cout << "Copied Object: ";
obj2.display();
obj2.setValue(500);
cout << "\nAfter modifying copied object:\n";
cout << "Original Object: ";
obj1.display();
cout << "Copied Object: ";
obj2.display();
return 0;
}

Output:

Original Object: Value: 100
Copied Object: Value: 100
After modifying copied object:
Original Object: Value: 100
Copied Object: Value: 500

Explanation:

  • Demo(int value) allocates memory dynamically using new.

  • Demo(const Demo& obj) is the copy constructor.

  • The expression new int(*obj.ptr) allocates new memory and copies the value stored at the original pointer.

  • Both objects now have separate memory locations.

  • Changing the copied object's value does not change the original object's value.

  • The destructor releases the memory owned by each object.

हिन्दी में समझें:

  • Demo(int value) constructor new की सहायता से dynamically memory allocate करता है।

  • Demo(const Demo& obj) एक copy constructor है।

  • new int(*obj.ptr) नई memory allocate करता है और original pointer पर stored value को copy करता है।

  • अब दोनों objects के पास अलग-अलग memory locations हैं।

  • Copied object की value बदलने पर original object की value नहीं बदलती।

  • Destructor प्रत्येक object की अपनी memory को release करता है।

How Does Deep Copy Work in C++?

Deep copy works by allocating fresh memory for the copied object and copying the actual contents from the source object.

Deep Copy में copied object के लिए नई memory allocate की जाती है और source object से वास्तविक data copy किया जाता है।

The process can be understood through the following steps:

  1. An object is created and dynamic memory is allocated.

  2. Another object is initialized using the first object.

  3. The copy constructor is called.

  4. The copy constructor allocates a new memory location.

  5. The value from the original memory is copied into the newly allocated memory.

  6. Both objects can now modify their data independently.

इस प्रक्रिया को निम्न चरणों से समझा जा सकता है:

  1. एक object बनाया जाता है और उसके लिए dynamic memory allocate की जाती है।

  2. पहले object की सहायता से दूसरा object initialize किया जाता है।

  3. Copy constructor call होता है।

  4. Copy constructor एक नई memory location allocate करता है।

  5. Original memory की value नई memory में copy की जाती है।

  6. अब दोनों objects अपने data को स्वतंत्र रूप से modify कर सकते हैं।

Deep Copy Using a Copy Constructor

A copy constructor is a special constructor that creates an object from another object of the same class. When a class manages dynamically allocated memory, a user-defined copy constructor may be required to perform a deep copy.

Copy constructor एक special constructor है जो उसी class के दूसरे object से नया object बनाता है। जब कोई class dynamically allocated memory को manage करती है, तब Deep Copy करने के लिए user-defined copy constructor की आवश्यकता हो सकती है।

Syntax:

ClassName(const ClassName& object) {
// Allocate new memory
// Copy the actual data
}

Here, const ClassName& accepts the source object by constant reference. Passing by reference avoids creating another copy while initializing the new object.

यहाँ const ClassName& source object को constant reference के रूप में प्राप्त करता है। Reference का उपयोग करने से नया object initialize करते समय एक और copy बनने की समस्या नहीं होती।

Example:

#include <iostream>
using namespace std;
class Number {
private:
int* data;
public:
Number(int value) {
data = new int(value);
}
Number(const Number& obj) {
data = new int(*obj.data);
}
~Number() {
delete data;
}
void display() const {
cout << *data << endl;
}
};
int main() {
Number n1(50);
Number n2(n1);
n1.display();
n2.display();
return 0;
}

Output:

50
50

Explanation: The copy constructor creates a new integer memory location for n2 and copies the value from n1. Therefore, both objects contain the same value but own separate memory.

व्याख्या: Copy constructor n2 के लिए एक नई integer memory location बनाता है और n1 की value को उसमें copy करता है। इसलिए दोनों objects में value समान है, लेकिन उनकी memory अलग-अलग है।

Deep Copy Using Copy Assignment Operator

The copy assignment operator is used to copy the contents of an already existing object into another existing object of the same class.

Copy assignment operator का उपयोग किसी पहले से मौजूद object की contents को उसी class के दूसरे पहले से मौजूद object में copy करने के लिए किया जाता है।

A copy constructor and a copy assignment operator perform different tasks:

  • Copy constructor creates a new object from an existing object.

  • Copy assignment operator copies data into an already existing object.

Copy constructor और copy assignment operator अलग-अलग कार्य करते हैं:

  • Copy constructor किसी existing object से नया object बनाता है।

  • Copy assignment operator किसी पहले से मौजूद object में data copy करता है।

Example:

#include <iostream>
using namespace std;
class Demo {
private:
int* ptr;
public:
Demo(int value) {
ptr = new int(value);
}
// Deep Copy Constructor
Demo(const Demo& obj) {
ptr = new int(*obj.ptr);
}
// Copy Assignment Operator
Demo& operator=(const Demo& obj) {
if (this != &obj) {
int* newPtr = new int(*obj.ptr);
delete ptr;
ptr = newPtr;
}
return *this;
}
~Demo() {
delete ptr;
}
void display() const {
cout << *ptr << endl;
}
};
int main() {
Demo obj1(100);
Demo obj2(200);
obj2 = obj1;
cout << "Object 1: ";
obj1.display();
cout << "Object 2: ";
obj2.display();
return 0;
}

Output:

Object 1: 100
Object 2: 100

Explanation:

  • obj1 and obj2 are two independently created objects.

  • The statement obj2 = obj1 calls the copy assignment operator.

  • A new memory location is allocated for the copied value.

  • The previous memory owned by obj2 is released.

  • The copied value is stored in the new memory location.

  • Both objects now contain independent copies of the same value.

हिन्दी में समझें:

  • obj1 और obj2 दो अलग-अलग objects हैं।

  • obj2 = obj1 statement copy assignment operator को call करता है।

  • Copy की जाने वाली value के लिए नई memory allocate होती है।

  • obj2 की पुरानी memory release कर दी जाती है।

  • नई memory में copied value store होती है।

  • अब दोनों objects के पास समान value की स्वतंत्र copies हैं।

The self-assignment check if (this != &obj) prevents an object from unnecessarily assigning itself. Allocating the new memory before deleting the old memory also helps avoid losing the existing data if allocation fails.

if (this != &obj) self-assignment check यह सुनिश्चित करता है कि object अनावश्यक रूप से स्वयं को assign न करे। पुरानी memory delete करने से पहले नई memory allocate करने से allocation failure की स्थिति में पुराने data को खोने से बचने में भी मदद मिलती है।


Advantages of Deep Copy in C++

Deep copy provides several benefits when objects manage their own dynamically allocated resources.

जब objects अपनी dynamically allocated resources को manage करते हैं, तब Deep Copy कई लाभ प्रदान करता है।

  1. Independent Objects: Each object maintains its own copy of dynamically allocated data.

    स्वतंत्र Objects: प्रत्येक object dynamically allocated data की अपनी अलग copy रखता है।

  2. Data Safety: Changes made to one object do not unintentionally modify another object's data.

    Data Safety: एक object में किए गए changes अनजाने में दूसरे object के data को modify नहीं करते।

  3. Better Memory Ownership: Each object can manage and release its own allocated memory.

    बेहतर Memory Ownership: प्रत्येक object अपनी allocated memory को स्वयं manage और release कर सकता है।

  4. Avoids Shared-Pointer Problems: Proper deep copying prevents multiple objects from incorrectly treating the same raw allocation as independently owned memory.

    Shared-Pointer समस्याओं से बचाव: सही Deep Copy multiple objects को एक ही raw memory allocation का स्वतंत्र owner मानने से रोकता है।

  5. Useful for Resource-Management Classes: Deep copying is useful when a class needs independent copies of dynamically allocated resources.

    Resource-Management Classes में उपयोगी: जब किसी class को dynamically allocated resources की स्वतंत्र copies चाहिए होती हैं, तब Deep Copy उपयोगी होता है।

Rule of Three in C++

The Rule of Three is an important C++ guideline for classes that directly manage resources such as dynamically allocated memory.

Rule of Three C++ का एक महत्वपूर्ण guideline है। यह उन classes के लिए उपयोगी है जो dynamically allocated memory जैसे resources को सीधे manage करती हैं।

According to the Rule of Three, if a class needs to define any one of the following special member functions, it will often need to define all three:

Rule of Three के अनुसार, यदि किसी class को निम्नलिखित special member functions में से किसी एक को define करने की आवश्यकता पड़ती है, तो अक्सर तीनों को define करना चाहिए:

  1. Destructor

  2. Copy Constructor

  3. Copy Assignment Operator

A destructor releases the resource, a copy constructor creates an independent copy when a new object is initialized, and a copy assignment operator handles copying into an already existing object.

Destructor resource को release करता है, copy constructor नया object initialize करते समय स्वतंत्र copy बनाता है, और copy assignment operator पहले से मौजूद object में copying का कार्य करता है।

The following example combines all three operations:

निम्न उदाहरण इन तीनों operations को एक साथ प्रदर्शित करता है:

#include <iostream>
using namespace std;
class Demo {
private:
int* ptr;
public:
Demo(int value) : ptr(new int(value)) {
}
// Copy Constructor
Demo(const Demo& other)
: ptr(new int(*other.ptr)) {
}
// Copy Assignment Operator
Demo& operator=(const Demo& other) {
if (this != &other) {
int* newPtr = new int(*other.ptr);
delete ptr;
ptr = newPtr;
}
return *this;
}
// Destructor
~Demo() {
delete ptr;
}
void setValue(int value) {
*ptr = value;
}
void display() const {
cout << "Value: " << *ptr << endl;
}
};
int main() {
Demo obj1(100);
Demo obj2 = obj1;
obj2.setValue(500);
cout << "Object 1: ";
obj1.display();
cout << "Object 2: ";
obj2.display();
Demo obj3(200);
obj3 = obj1;
cout << "Object 3: ";
obj3.display();
return 0;
}

Output:

Object 1: Value: 100
Object 2: Value: 500
Object 3: Value: 100

Explanation: The copy constructor creates obj2 as an independent copy of obj1. The copy assignment operator then copies obj1 into the already existing obj3. Each object owns a separate integer allocation, which is released by its destructor.

व्याख्या: Copy constructor obj1 की स्वतंत्र copy के रूप में obj2 बनाता है। इसके बाद copy assignment operator obj1 को पहले से मौजूद obj3 में copy करता है। प्रत्येक object अपनी अलग integer memory का owner है, जिसे उसका destructor release करता है।

Deep Copy in Modern C++

Modern C++ provides resource-management tools that can reduce the need to write manual deep-copy code.

Modern C++ में ऐसे resource-management tools उपलब्ध हैं जो manually Deep Copy code लिखने की आवश्यकता को कम कर सकते हैं।

For example, std::string and std::vector manage their own memory and support value-based copying. When copied, they provide independent values without requiring the programmer to manually allocate and release their internal memory.

उदाहरण के लिए, std::string और std::vector अपनी memory को स्वयं manage करते हैं और value-based copying support करते हैं। इन्हें copy करने पर independent values मिलती हैं और programmer को उनकी internal memory manually allocate या release नहीं करनी पड़ती।

Example using std::vector:

#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v1 = {10, 20, 30};
vector<int> v2 = v1;
v2[0] = 100;
cout << "Original Vector: ";
for (int value : v1) {
cout << value << " ";
}
cout << "\nCopied Vector: ";
for (int value : v2) {
cout << value << " ";
}
return 0;
}

Output:

Original Vector: 10 20 30
Copied Vector: 100 20 30

Explanation: The vector copy creates an independent container. Modifying an element in v2 does not change the corresponding element in v1.

व्याख्या: Vector की copy एक स्वतंत्र container बनाती है। v2 के किसी element को modify करने पर v1 का corresponding element नहीं बदलता।

For classes that manage resources, modern C++ generally recommends the Rule of Zero: prefer standard library types and RAII so that the compiler-generated special member functions can manage copying and destruction safely. If a class needs exclusive ownership of a resource, std::unique_ptr is useful, but it is not copyable by default; copying such a class requires an explicitly designed copy operation or a different ownership model.

Resources manage करने वाली classes के लिए Modern C++ में सामान्यतः Rule of Zero की सलाह दी जाती है। Standard library types और RAII का उपयोग करने से compiler-generated special member functions copying और destruction को सुरक्षित तरीके से manage कर सकते हैं। यदि किसी class को किसी resource का exclusive ownership चाहिए, तो std::unique_ptr उपयोगी है, लेकिन यह default रूप से copyable नहीं होता। ऐसी class को copy करने के लिए अलग से copy operation design करना या ownership का दूसरा model चुनना आवश्यक है।

Frequently Asked Questions (FAQs)

1. What is Deep Copy in C++?

Deep copy creates an independent copy of an object by copying its data into separately allocated memory where necessary.

Deep Copy किसी object के data को आवश्यकतानुसार अलग से allocated memory में copy करके उसकी स्वतंत्र copy बनाता है।

2. Why is Deep Copy required in C++?

Deep copy is required when objects manage dynamically allocated resources and must maintain independent ownership of those resources.

जब objects dynamically allocated resources को manage करते हैं और उनका independent ownership बनाए रखना चाहते हैं, तब Deep Copy की आवश्यकता होती है।

3. Which constructor is used for Deep Copy?

A user-defined copy constructor is commonly used to implement deep copying when a class owns dynamically allocated memory.

जब किसी class के पास dynamically allocated memory का ownership होता है, तब Deep Copy implement करने के लिए सामान्यतः user-defined copy constructor का उपयोग किया जाता है।

4. What is the difference between a copy constructor and a copy assignment operator?

A copy constructor initializes a new object from an existing object, whereas a copy assignment operator copies data into an already existing object.

Copy constructor किसी existing object से नया object initialize करता है, जबकि copy assignment operator पहले से मौजूद object में data copy करता है।

5. Does the default copy constructor perform Deep Copy?

No. The implicitly defined copy constructor performs memberwise copying. For raw pointer members, this copies pointer values rather than the dynamically allocated data.

नहीं। Compiler द्वारा implicitly defined copy constructor memberwise copying करता है। Raw pointer members के मामले में यह dynamically allocated data के बजाय pointer values को copy करता है।

6. Can Deep Copy prevent double deletion?

A correctly implemented deep copy gives each object its own allocation, so each destructor can release its own memory without deleting the same allocation twice.

सही तरीके से implement की गई Deep Copy प्रत्येक object को अलग memory allocation देती है। इसलिए प्रत्येक destructor अपनी memory release कर सकता है और एक ही allocation को दो बार delete करने की समस्या से बचा जा सकता है।

7. What is the Rule of Three in C++?

The Rule of Three states that a class managing resources may need a destructor, copy constructor, and copy assignment operator together.

Rule of Three के अनुसार, resources manage करने वाली class को destructor, copy constructor और copy assignment operator तीनों define करने की आवश्यकता हो सकती है।

8. Is Deep Copy always necessary in C++?

No. Standard library containers and resource-management types often handle copying safely. Manual deep copying is mainly needed when a class directly manages resources and requires independent copies.

नहीं। Standard library containers और resource-management types अक्सर copying को सुरक्षित तरीके से manage करते हैं। Manual Deep Copy मुख्य रूप से तब आवश्यक होती है जब कोई class resources को सीधे manage करती है और independent copies चाहती है।

Deep Copy is an important concept in C++ object copying, especially when a class contains pointers and dynamically allocated memory. It creates independent copies of data and helps avoid unintended sharing and memory-management problems. A proper understanding of copy constructors, copy assignment operators, destructors, and the Rule of Three helps programmers design safer resource-managing classes. In modern C++, RAII and standard library containers should generally be preferred over manually managed raw pointers.

C++ में Deep Copy object copying की एक महत्वपूर्ण अवधारणा है, विशेष रूप से तब जब किसी class में pointers और dynamically allocated memory होती है। यह data की independent copies बनाती है और अनजाने में memory sharing तथा memory-management समस्याओं से बचने में मदद करती है। Copy constructors, copy assignment operators, destructors और Rule of Three की सही समझ programmers को अधिक सुरक्षित resource-managing classes बनाने में मदद करती है। Modern C++ में manually managed raw pointers के स्थान पर सामान्यतः RAII और standard library containers को प्राथमिकता देनी चाहिए।

Comments

Popular posts from this blog

Important Questions (IMP) of Programming Methodologies and Data structures using C++ with OOP's Concepts

Complete C++ Programming Course - OOP and Modern C++

OOP's using CPP Syllabus AND Programming Methodologies and Data Structures Using C++ (NEP 2020)