AnyCompiler

Smart Pointers

Ek unique_ptr ek heap-allocated object ko exclusively own karta hai — jab yeh scope se bahar jaata hai, to iska destructor automatically us object ko delete kar deta hai jiska yeh owner hai, is course mein pehle wale RAII pattern par directly inhisar karte hue. make_unique hath se kabhi new ya delete likhe baghair ek banata hai.

#include <iostream>
#include <memory>
using namespace std;

class Resource {
public:
    Resource() { cout << "Resource acquired" << endl; }
    ~Resource() { cout << "Resource released" << endl; }
    void use() { cout << "Using resource" << endl; }
};

int main() {
    unique_ptr<Resource> res = make_unique<Resource>();
    res->use();
    return 0;
}
Output
Resource acquired
Using resource
Resource released

shared_ptr

Ek shared_ptr same object ke multiple owners allow karta hai, ek reference count se track karte hue ke abhi kitne shared_ptrs use point kar rahe hain. Object tabhi destroy hota hai jab woh count zero tak drop hota hai — useful hai jab ek single, clear owner genuinely possible na ho.

#include <iostream>
#include <memory>
using namespace std;

int main() {
    shared_ptr<int> a = make_shared<int>(42);
    shared_ptr<int> b = a;
    cout << "value = " << *a << endl;
    cout << "use_count = " << a.use_count() << endl;
    return 0;
}
Output
value = 42
use_count = 2

Modern C++ code by default unique_ptr aur shared_ptr ka istemal karta hai, aur raw new/delete ko ek last resort ki tarah treat karta hai — smart pointers aapko kisi bhi doosre RAII type jaisa hi deterministic cleanup dete hain, bina programmer ko manually delete call karna yaad rakhna pare.

Aage: exceptions aur error handling — try, catch, aur throw.

Practice exercise

make_unique istemal kar ke ek unique_ptr<int> banayein jo value 99 hold kare, phir woh value print karein jispar yeh point karta hai.