5.2.8 · HinglishC++ Programming

Copy constructor and copy assignment — Rule of Three

1,840 words8 min readRead in English

5.2.8 · Coding › C++ Programming


WHAT are these three things?

Key distinction yeh hai:

MyString a = b;   // copy CONSTRUCTOR (a abhi born ho raha hai)
MyString c;
c = b;            // copy ASSIGNMENT  (c already exist karta hai)

WHY does the compiler-generated version break? (Shallow vs Deep)

Figure — Copy constructor and copy assignment — Rule of Three

Shallow copy ka aftermath:

a.data ──┐
         ├──► [ "hi\0" ]      ek buffer, do owners
b.data ──┘

Jab a aur b dono destruct hote hain: delete[] (same ptr) do baar run hota hai → undefined behavior. Saath hi, a ke through likhna silently b ko corrupt karta hai (aliasing).


HOW to write them — scratch se ek safe MyString banana

Humein ek class chahiye jo char* own kare. Chaliye har member ko reason karke banate hain ki kya hona chahiye.

#include <cstring>   // strlen, strcpy
 
class MyString {
    char* data;      // owned resource
    std::size_t len;
 
public:
    // --- normal constructor ---
    MyString(const char* s = "") {
        len  = std::strlen(s);
        data = new char[len + 1];   // +1 '\0' ke liye
        std::strcpy(data, s);
    }

len+1 kyun? Strings ko null terminator slot chahiye hota hai.

    // --- (1) Destructor: resource kaise marta hai ---
    ~MyString() {
        delete[] data;              // [] kyunki humne new[] kiya tha
    }

delete[] kyun? Array-new ko array-delete ke saath pair karna zaroori hai, warna UB.

    // --- (2) Copy constructor: copy ke roop mein born hona ---
    MyString(const MyString& other) {
        len  = other.len;
        data = new char[len + 1];   // APNA memory — deep copy
        std::strcpy(data, other.data);
    }

Fresh allocate kyun karte hain? Taaki naya object ek independent buffer own kare; ek ko destroy karna doosre ko affect na kare.

    // --- (3) Copy assignment: ek existing object ko overwrite karna ---
    MyString& operator=(const MyString& other) {
        if (this == &other) return *this;   // self-assignment guard
        delete[] data;                      // PURANA resource free karo
        len  = other.len;
        data = new char[len + 1];           // naya allocate karo
        std::strcpy(data, other.data);
        return *this;                        // chaining a=b=c ke liye
    }
};

WHY operator= ki har line exist karti hai (steel-manned)


Worked examples


Modern footnote: Rule of Five & Rule of Zero


Active recall

Rule of Three kaunse teen members se concerned hai?
Destructor, copy constructor, aur copy assignment operator.
Rule of Three kyun exist karta hai?
Agar ek class manually resource manage karti hai, toh double-free, leaks, aur aliasing bugs se bachne ke liye teeno ki zaroorat hoti hai.
Copy constructor vs copy assignment ko trigger se distinguish karo.
Copy ctor: ek naya object doosre se create hota hai. Copy assignment: ek already-existing object overwrite hota hai.
Shallow copy vs deep copy kya hota hai?
Shallow pointer copy karta hai (shared buffer); deep naya memory allocate karta hai aur contents copy karta hai.
Pointer ki default shallow copy se do bugs kya hain?
Destruction par double free, aur aliasing (ek mein likhna doosre ko corrupt karta hai).
Copy assignment mein self-assignment guard kyun lagana hoga?
Iske bina, data ko copy karne se pehle free karna source ko destroy kar deta hai (jaise a = a).
operator= ko purana resource kyun free karna chahiye lekin copy ctor ko nahi?
Assigned-to object already ek buffer own karta hai (free nahi kiya toh leak); constructed object ke paas abhi koi buffer nahi hota.
Copy assignment ke liye conventional signature kya hai?
T& operator=(const T& other) — chaining ke liye reference return karta hai.
Copy-and-swap tumhe kya deta hai?
Value parameter se copy karke phir swap karne se self-assignment safety aur exception safety free mein milti hai.
new[] ko delete[] ke saath kyun pair karna chahiye?
Mismatched new/delete forms undefined behavior hai.
Rule of Zero kya hai?
RAII member types (string, vector, unique_ptr) use karo taaki tum special members mein se koi bhi na likho.

Recall Feynman: ek 12-saal ke bacche ko explain karo

Socho har object ke paas ek toy box (memory) hai aur ek note jis par box ka address likha hai. Lazy copy sirf note ko photocopy karta hai, toh ab do bacche ek hi box ko point karte hain. Jab playtime khatam hoti hai, dono bacche box ko phenkne ki koshish karte hain — lekin ek hi box ko do baar nahi phek sakte, toh sab kuch toot jaata hai! Rule of Three kehta hai: agar tumne kisi bacche ko ek box diya, toh tumhe unhe teen cheezein sikhani hain — box ko saaf karna, janam lete waqt box ki apni copy banana, aur baad mein box badalna apni copy se. Teeno karo ya koi nahi.


Connections

Concept Map

triggers need for

compiler gives

does

causes

leads to

requires

requires

requires

releases resource with delete[]

must perform

must perform

fixes

needs

prevents freeing before copy

Class owns a resource

Default copy is member-wise

Shallow copy of pointer

Two objects share one buffer

Double free and aliasing bugs

Rule of Three

Destructor ~T

Copy constructor T const T&

Copy assignment operator=

Deep copy allocates new memory

Self-assignment guard