All Courses
OOP: ADVANCED OOP TOPICS

Smart Pointers: unique_ptr and shared_ptr

Smart pointers are C++ objects that manage dynamically allocated memory automatically using RAII.

RAII means:

Resource Acquisition Is Initialization.

The resource is acquired by an object and released by that object's destructor.

Smart pointers are not garbage collection. They are ownership wrappers.

Why Raw new/delete Is Risky

Raw pointer style:

// Student* s = new Student();
// delete s;

If delete is forgotten, memory leaks.

Smart pointers reduce this risk.

unique_ptr

unique_ptr means one owner.

Only one smart pointer owns the object at a time.

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

class Student {
public:
    Student() {
        cout << "Student created" << endl;
    }

    ~Student() {
        cout << "Student destroyed" << endl;
    }

    void study() const {
        cout << "Studying" << endl;
    }
};

int main() {
    unique_ptr<Student> student = make_unique<Student>();
    student->study();

    return 0;
}

Output:

Student created
Studying
Student destroyed

Moving unique_ptr

unique_ptr cannot be copied. Ownership must be moved.

unique_ptr<Student> a = make_unique<Student>();
unique_ptr<Student> b = move(a);

After the move, b owns the object.

shared_ptr

shared_ptr means shared ownership.

It keeps a reference count. The object is destroyed when the last shared_ptr owner is gone.

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

class Course {
public:
    Course() {
        cout << "Course created" << endl;
    }

    ~Course() {
        cout << "Course destroyed" << endl;
    }
};

int main() {
    shared_ptr<Course> c1 = make_shared<Course>();
    shared_ptr<Course> c2 = c1;

    cout << "Owners: " << c1.use_count() << endl;

    return 0;
}

Output:

Course created
Owners: 2
Course destroyed

unique_ptr vs shared_ptr

Smart pointer Ownership Copy allowed? Use when
unique_ptr single owner no one clear owner
shared_ptr shared owners yes multiple owners need shared lifetime

Prefer unique_ptr by default. Use shared_ptr only when shared ownership is truly needed.

Viva Answer

Smart pointers manage dynamic memory using RAII. unique_ptr represents exclusive ownership and cannot be copied, only moved. shared_ptr represents shared ownership using reference counting and destroys the object when the last owner is gone.

Quick Check

  1. Are smart pointers garbage collection?
  2. Which smart pointer has exactly one owner?
  3. Which smart pointer uses reference counting?