TalentJR

🧩 C++ programming tutorial for beginners · Class 11 · Lesson 14 of 18 · Free

Smart Pointers in C++ – unique_ptr, shared_ptr and weak_ptr

⏱ About 35 minutes · ▶ run real C++ here — nothing to install · no sign-in

In this lesson you will

  • Explain why raw new and delete cause leaks
  • Own an object with unique_ptr and pass ownership with std::move
  • Share an object with shared_ptr and break cycles with weak_ptr

A library lends a book and writes down who has it. If nobody ever returns it, the shelf slowly empties. Memory made with new is the same: if nobody calls delete, it is lost until the program ends. Smart pointers remember to give memory back for you.

Why are new and delete risky in C++?

In Lesson 7 you saw that delete runs the destructor and frees the memory. With a raw pointer (a normal Book*), YOU must remember to call delete exactly once.

Forget it, and the memory is never given back. This is a memory leak. Call it twice, or use the pointer after delete, and the program has undefined behaviour.

Look at the output below: the first book is cleaned up, the second never is. A program that runs for days (like a server) can slowly run out of memory this way.

🧩 C++ — you can edit this code
Output
Got Wings of Fire
Got Malgudi Days
Returned Wings of Fire
End of main

What is unique_ptr in C++ and how do you use make_unique?

A smart pointer is an object that holds a pointer and deletes it in its own destructor. They live in the <memory> header.

unique_ptr is the simplest one: exactly one owner. make_unique<Book>(...) creates the object and the unique_ptr together. Use -> and * just like a raw pointer.

When the unique_ptr goes out of scope, the object is deleted automatically, even if you return early. Try it: add a third book inside the inner { } block and watch when it is returned.

🧩 C++ — you can edit this code
Output
Got Wings of Fire
Reading Wings of Fire
Got Malgudi Days
Reading Malgudi Days
Returned Malgudi Days
End of main
Returned Wings of Fire

How do you move a unique_ptr to a new owner in C++?

A unique_ptr cannot be copied, because then two owners would both delete the same object. It can be MOVED with std::move: ownership passes over and the old pointer becomes empty (nullptr).

A function that takes unique_ptr by value takes ownership. A function that only needs to look at the object should take a plain reference instead.

A vector of unique_ptr to a base class is a common way to keep a list of different child objects (Lesson 13). When the vector dies, every object is deleted.

🧩 C++ — you can edit this code
Output
Looking at Panchatantra
mine is empty
Shelf has 2 books
Freed Godaan
Freed Panchatantra

What is shared_ptr in C++ and what does use_count mean?

Sometimes many parts of a program need the same object. For example, three sections share one class notice. Nobody is the single owner.

shared_ptr keeps a count of how many shared_ptrs point to the object. use_count() shows it. Copying adds 1; a copy going away subtracts 1.

When the count reaches 0, the object is deleted. Try it: make a fourth copy inside the block and watch the numbers.

🧩 C++ — you can edit this code
Output
count 1
count 3
Holiday on Friday
count 1
Notice removed
End of main

What is weak_ptr in C++ and when do you need it?

A weak_ptr watches an object owned by shared_ptrs but does not count as an owner. It does not keep the object alive.

To use it, call lock(). It gives a shared_ptr if the object still exists, or an empty one if it is gone. expired() tells you if it is gone.

weak_ptr also fixes cycles: if A and B hold shared_ptrs to each other, their counts never reach 0 and both leak. Make one of the links a weak_ptr (see the mistakes below).

🧩 C++ — you can edit this code
Output
owners: 1
score is 287
expired? yes
nothing to read

🤔 Predict the output

Think like C++: read the code and choose what it prints. You get the reason straight away.

Question 1. What does this print?

auto a = make_shared<int>(5);
auto b = a;
{
    auto c = a;
    cout << a.use_count();
}
cout << a.use_count() << "\n";

Question 2. What does this print?

auto p = make_unique<int>(10);
auto q = std::move(p);
cout << (p ? "p full" : "p empty") << ", " << *q << "\n";

Question 3. In what order are the objects deleted?

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

struct Tag {
    char c;
    Tag(char x) : c(x) {}
    ~Tag() { cout << c; }
};

int main() {
    auto a = make_unique<Tag>('A');
    auto b = make_unique<Tag>('B');
    auto c = make_unique<Tag>('C');
    cout << "-";
    return 0;
}

🧩 Your challenge

A school library shelf is a vector<unique_ptr<Book>>. Write issueBook: it finds a book by title on the shelf, MOVES it into the student's bag (another vector<unique_ptr<Book>>), erases the empty slot from the shelf and returns true; it returns false if the title is not there. Expected output: Issued Godaan: yes Issued Gitanjali: no Shelf: 2, Bag: 1 Freed Godaan Freed Panchatantra Freed Malgudi Days

Expected output :
Issued Godaan: yes
Issued Gitanjali: no
Shelf: 2, Bag: 1
Freed Godaan
Freed Panchatantra
Freed Malgudi Days
🧩 C++ — you can edit this code

⚠️ Common mistakes (and how to fix them)

❌ Wrong

auto a = make_unique<int>(42);
unique_ptr<int> b = a;
cout << *b << "\n";

Line 2: error: call to implicitly-deleted copy constructor of 'unique_ptr<int>'

✅ Right

auto a = make_unique<int>(42);
unique_ptr<int> b = std::move(a);
cout << *b << "\n";

unique_ptr cannot be copied — there may be only one owner. Use std::move to hand ownership over, or use shared_ptr if you really need two owners.

❌ Wrong

unique_ptr<int> p = new int(5);
cout << *p << "\n";

Line 1: error: no viable conversion from 'int *' to 'unique_ptr<int>'

✅ Right

unique_ptr<int> p = make_unique<int>(5);
cout << *p << "\n";

A raw pointer does not turn into a unique_ptr with =, to stop accidents. Use make_unique (or make_shared): it is shorter and never leaks.

❌ Wrong

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

struct Student;
struct Mentor {
    shared_ptr<Student> student;
    ~Mentor() { cout << "Mentor freed\n"; }
};
struct Student {
    shared_ptr<Mentor> mentor;
    ~Student() { cout << "Student freed\n"; }
};

int main() {
    auto m = make_shared<Mentor>();
    auto s = make_shared<Student>();
    m->student = s;
    s->mentor = m;
    cout << "End of main\n";
    return 0;
}

Compiles and runs, but prints: End of main ⏎

✅ Right

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

struct Student;
struct Mentor {
    weak_ptr<Student> student;      // watches, does not own
    ~Mentor() { cout << "Mentor freed\n"; }
};
struct Student {
    shared_ptr<Mentor> mentor;
    ~Student() { cout << "Student freed\n"; }
};

int main() {
    auto m = make_shared<Mentor>();
    auto s = make_shared<Student>();
    m->student = s;
    s->mentor = m;
    cout << "End of main\n";
    return 0;
}

Two shared_ptrs pointing at each other keep each other's count above 0, so neither is ever freed (a leak). Make one link a weak_ptr.

📌 Remember

  • Raw new/delete is easy to get wrong: forgetting delete leaks memory.
  • unique_ptr has one owner and deletes the object when it goes out of scope.
  • Create with make_unique / make_shared; move a unique_ptr with std::move.
  • shared_ptr counts its owners (use_count) and deletes at zero.
  • weak_ptr watches without owning; use lock() and use it to break cycles.
  • Prefer unique_ptr; use shared_ptr only when ownership really is shared.

Finished the quiz and the challenge?

Questions students ask

What are smart pointers in C++?

They are class objects from <memory> that hold a pointer and delete it automatically in their destructor. The main ones are unique_ptr, shared_ptr and weak_ptr.

unique_ptr or shared_ptr — which should I use?

Use unique_ptr by default: it is simple and has no extra cost. Use shared_ptr only when several parts of the program truly own the same object and you cannot say which one finishes last.

Should I still use new and delete in modern C++?

Rarely in everyday code. Containers like vector and smart pointers handle memory for you. You still need to understand new and delete to read older code.

Does C++ have garbage collection?

No. C++ frees memory at exact, known points: when an owner (a variable, a container or a smart pointer) is destroyed. That is why destructors and smart pointers matter so much.