LearnFrenzy
Sign in Take a free test

C++ Programming · Topic 22 of 27

Smart Pointers

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

Smart Pointers · Study material

Smart pointers in C++ are objects that own dynamically allocated memory and free it automatically. With raw new and delete, every early return, exception or forgotten delete is a memory leak, and deleting twice or using memory after delete crashes the program. std::unique_ptr, std::shared_ptr and std::weak_ptr from <memory> make ownership explicit and cleanup automatic – this is RAII applied to memory, and it is the reason modern C++ code almost never calls delete. "unique_ptr vs shared_ptr", "how does reference counting work", "what is weak_ptr for" and "how do you break a cycle" are classic interview questions. This page answers all of them with programs you can run. Then practise with 60 questions – 20 MCQs, 20 predict-the-output puzzles, 10 find-the-error programs and 10 complete programs – verified on a real C++ compiler.

On this page

  • Why raw owning pointers are dangerous
  • std::unique_ptr: exclusive ownership, move, get, release, reset, arrays, custom deleters
  • std::shared_ptr: shared ownership, reference counting, make_shared, control block
  • std::weak_ptr: observing, lock(), breaking cycles
  • enable_shared_from_this and how to pass smart pointers to functions

Why smart pointers?

A raw pointer from new does not know it owns anything. If an exception is thrown or a function returns early before delete, the memory leaks. A smart pointer is a small object whose destructor deletes what it owns, so cleanup happens on every path – including stack unwinding.

#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>

struct File {
    std::string name;
    explicit File(std::string n) : name(std::move(n)) { std::cout << "open " << name << '\n'; }
    ~File() { std::cout << "close " << name << '\n'; }
};

void raw_version(bool fail) {
    File* f = new File("raw.txt");
    if (fail) throw std::runtime_error("oops");   // LEAK: delete is never reached
    delete f;
}

void smart_version(bool fail) {
    auto f = std::make_unique<File>("smart.txt");  // owner: deletes automatically
    if (fail) throw std::runtime_error("oops");    // still closed during stack unwinding
}

int main() {
    try { smart_version(true); } catch (const std::exception& e) { std::cout << "caught " << e.what() << '\n'; }
    raw_version(false);                            // fine only on the happy path
    return 0;
}

Output

open smart.txt
close smart.txt
caught oops
open raw.txt
close raw.txt

std::unique_ptr: exclusive ownership

unique_ptr owns its object alone. It cannot be copied, only moved, which transfers ownership and leaves the source empty. It is as small and fast as a raw pointer (zero overhead with the default deleter), so it should be your default. Create it with std::make_unique<T>(args…).

#include <iostream>
#include <memory>
#include <string>

struct Player {
    std::string name;
    int score = 0;
    explicit Player(std::string n) : name(std::move(n)) {}
    ~Player() { std::cout << "~" << name << ' '; }
};

int main() {
    std::unique_ptr<Player> p = std::make_unique<Player>("Asha");
    p->score = 90;                                  // use like a pointer
    std::cout << (*p).name << ' ' << p->score << ' ' << (p != nullptr) << '\n';

    // std::unique_ptr<Player> copy = p;            error: unique_ptr cannot be copied
    std::unique_ptr<Player> q = std::move(p);       // ownership MOVES; p becomes empty
    std::cout << (p == nullptr) << ' ' << q->name << '\n';

    Player* observer = q.get();                     // non-owning raw pointer (do not delete!)
    q.reset(new Player("Ravi"));                    // deletes Asha, now owns Ravi
    std::cout << "| " << q->name << ' ' << (observer != q.get()) << '\n';
    return 0;                                       // deletes Ravi
}

Output

Asha 90 1
1 Asha
~Asha | Ravi 1
~Ravi
MemberEffect
get()raw pointer, ownership kept
release()gives up ownership, returns the raw pointer (you must delete it)
reset(p)deletes the current object, takes p (or nothing)
operator booltrue if it owns something
*, ->access the object

unique_ptr with arrays, polymorphism and custom deleters

unique_ptr<T[]> calls delete[] and provides []. A unique_ptr<Base> can own a Derived object (the base needs a virtual destructor). A custom deleter lets unique_ptr manage any resource – files, sockets, C library handles.

#include <cstdio>
#include <iostream>
#include <memory>
#include <vector>

struct Shape {
    virtual double area() const = 0;
    virtual ~Shape() = default;
};
struct Square : Shape { double s; explicit Square(double x) : s(x) {} double area() const override { return s * s; } };

int main() {
    // Arrays: unique_ptr<T[]> calls delete[]
    auto buf = std::make_unique<int[]>(5);
    for (int i = 0; i < 5; ++i) buf[i] = i * i;
    std::cout << buf[4] << ' ';

    // Polymorphism: unique_ptr<Base> owning a Derived
    std::vector<std::unique_ptr<Shape>> shapes;
    shapes.push_back(std::make_unique<Square>(3));
    std::cout << shapes[0]->area() << ' ';

    // Custom deleter: manage a C resource (here a FILE*)
    auto closer = [](std::FILE* f) { if (f) { std::fclose(f); std::cout << "fclose "; } };
    {
        std::unique_ptr<std::FILE, decltype(closer)> f(std::tmpfile(), closer);
        std::fputs("hello", f.get());
    }
    std::cout << sizeof(std::unique_ptr<int>) << '\n';
    return 0;
}

Output

16 9 fclose 8

std::shared_ptr: shared ownership

Several shared_ptrs can own the same object. They share a control block holding a reference count; copying increments it, destroying or resetting decrements it, and the object is deleted when it reaches zero. std::make_shared allocates the object and control block together in one allocation.

#include <iostream>
#include <memory>
#include <string>
#include <vector>

struct Config {
    std::string theme;
    explicit Config(std::string t) : theme(std::move(t)) {}
    ~Config() { std::cout << "Config freed\n"; }
};

int main() {
    auto cfg = std::make_shared<Config>("dark");          // count = 1
    std::cout << cfg.use_count() << ' ';
    {
        std::shared_ptr<Config> a = cfg;                   // copy: count = 2
        std::vector<std::shared_ptr<Config>> users(3, cfg);   // count = 5
        std::cout << cfg.use_count() << ' ';
        a->theme = "light";                                // all owners see the same object
    }                                                      // a and the vector are gone: count = 1
    std::cout << cfg.use_count() << ' ' << cfg->theme << '\n';
    cfg.reset();                                           // last owner: the object is freed
    std::cout << "end\n";
    return 0;
}

Output

1 5 1 light
Config freed
end

std::weak_ptr: observing without owning

A weak_ptr refers to an object managed by shared_ptrs but does not keep it alive. To use the object, call lock(), which returns a shared_ptr – empty if the object is already gone. Typical uses: caches, observers and back-pointers.

#include <iostream>
#include <memory>

int main() {
    std::weak_ptr<int> watcher;
    {
        auto data = std::make_shared<int>(42);
        watcher = data;                                   // observes, does NOT own
        std::cout << data.use_count() << ' ' << watcher.expired() << ' ';
        if (auto locked = watcher.lock())                 // temporary shared_ptr if still alive
            std::cout << *locked << ' ' << data.use_count() << ' ';
    }                                                     // data destroyed here
    std::cout << watcher.expired() << ' ' << (watcher.lock() == nullptr) << '\n';
    return 0;
}

Output

1 0 42 2 1 1

Reference cycles

If two objects own each other through shared_ptrs, their counts never reach zero and both leak. Make one direction (usually the "back" or "parent" link) a weak_ptr.

#include <iostream>
#include <memory>
#include <string>

struct Employee;
struct Team {
    std::string name;
    std::shared_ptr<Employee> lead;
    ~Team() { std::cout << "~Team "; }
};
struct Employee {
    std::string name;
    std::weak_ptr<Team> team;          // weak: breaks the cycle (shared_ptr here would leak both)
    ~Employee() { std::cout << "~Employee "; }
};

int main() {
    {
        auto t = std::make_shared<Team>();
        auto e = std::make_shared<Employee>();
        t->name = "Platform"; e->name = "Asha";
        t->lead = e;
        e->team = t;
        if (auto tm = e->team.lock()) std::cout << e->name << " leads " << tm->name << '\n';
        std::cout << t.use_count() << ' ' << e.use_count() << '\n';
    }
    std::cout << "| both freed\n";
    return 0;
}

Output

Asha leads Platform
1 2
~Team ~Employee | both freed

enable_shared_from_this

An object managed by shared_ptr sometimes needs a shared_ptr to itself – for example to keep itself alive in a callback. Creating shared_ptr<T>(this) would make a second, independent control block and a double delete. Derive from std::enable_shared_from_this<T> and call shared_from_this() instead.

#include <functional>
#include <iostream>
#include <memory>
#include <vector>

std::vector<std::function<void()>> pending;      // callbacks to run later

class Session : public std::enable_shared_from_this<Session> {
    int id_;
public:
    explicit Session(int id) : id_(id) {}
    ~Session() { std::cout << "~Session " << id_ << '\n'; }
    void start() {
        // shared_from_this() gives a shared_ptr that shares ownership with the existing one,
        // so the session stays alive until the callback has run
        pending.push_back([self = shared_from_this()] { std::cout << "callback for " << self->id_ << '\n'; });
    }
};

int main() {
    {
        auto s = std::make_shared<Session>(7);
        s->start();
        std::cout << "use_count " << s.use_count() << '\n';
    }                                            // s is gone, but the callback keeps the session alive
    for (auto& f : pending) f();
    pending.clear();                             // last owner released here
    std::cout << "done\n";
    return 0;
}

Output

use_count 2
callback for 7
~Session 7
done

Which smart pointer should I use?

unique_ptrshared_ptrweak_ptr
Ownershipexclusiveshared (reference counted)none (observer)
Copyableno (move only)yesyes
Size (64-bit, typical)8 bytes16 bytes + control block16 bytes
Costnoneatomic count updates, extra allocation (unless make_shared)lock() cost
Use forthe default; factories; members; containers of polymorphic objectsgenuinely shared lifetime (caches, graphs, async tasks)breaking cycles, caches, observers

Common mistakes

  • Two smart pointers from one raw pointer – shared_ptr<T> a(p), b(p); deletes twice.
  • Deleting the result of get() – the smart pointer will delete it again.
  • shared_ptr<T>(this) – use enable_shared_from_this.
  • Cycles of shared_ptr – memory never freed; use weak_ptr for one direction.
  • Using a moved-from unique_ptr – it is null.
  • Using shared_ptr by default – it is slower and hides who owns what; start with unique_ptr.
  • unique_ptr<T> for new T[n] – use unique_ptr<T[]> or std::vector.

Key points to remember

  • Prefer make_unique / make_shared over new.
  • unique_ptr: one owner, move-only, zero overhead – the default.
  • shared_ptr: many owners, reference count, object freed when the last owner goes.
  • weak_ptr: non-owning; lock() to use; breaks cycles.
  • Pass T& to functions that only use the object; pass smart pointers only to transfer or share ownership.
  • Polymorphic bases owned through smart pointers need virtual destructors.

Frequently asked questions

Is shared_ptr thread-safe?

The reference count is updated atomically, so copying and destroying shared_ptrs in different threads is safe. Access to the pointed-to object is not synchronised; protect it yourself. Modifying the same shared_ptr variable from several threads needs std::atomic<std::shared_ptr<T>> (C++20).

Why prefer make_shared?

One allocation for the object and control block instead of two, better cache locality, and no leak if another argument's evaluation throws.

Was auto_ptr removed?

Yes. std::auto_ptr (with surprising copy-means-move semantics) was deprecated in C++11 and removed in C++17; use unique_ptr.

Where can I learn more?

Read C++ Smart Pointers and C++ Move Semantics, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About C++ Programming

C++ adds object-oriented programming, templates and the powerful Standard Template Library (STL) to C. It powers game engines, browsers, trading systems and most competitive programming. This section takes you from basic syntax to classes, inheritance, polymorphism, modern C++ (C++11 to C++23) and the STL – every concept with runnable examples and practice questions checked on a real compiler.

Why it matters

  • OOP concepts – classes, inheritance, polymorphism, encapsulation – are asked in almost every interview
  • C++ with the STL is the most popular language for competitive programming and DSA rounds
  • Questions on constructors, virtual functions, references and smart pointers decide technical rounds
  • Modern C++ skills are in demand at product companies, fintech and game studios

Who it is for

  • School students (Class 11–12 computer science with C++) preparing for board exams and practicals
  • College students (B.Tech, BCA, MCA) learning OOP and data structures for semester exams and labs
  • Freshers preparing for placements, coding tests and C++ technical interviews
  • Competitive programmers who want to master the STL

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • Product company interviews
  • Coding rounds & DSA
  • Competitive programming
  • GATE CS
  • University exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links