Skip to content
binshelf/ cpp

Search lessons

Type a C++ term, like vector, reference, unique_ptr or use-after-free.

    Lessons

    On this page

    1. Key terms
    2. In 30 seconds
    3. std::unique_ptr: one owner
    4. A unique_ptr can’t be copied
    5. Handing over ownership with std::move
    6. std::shared_ptr: shared ownership
    7. Cycles and std::weak_ptr
    8. Raw pointers and references don’t own
    9. Which one should I use?
    10. Under the hood
    11. Common pitfalls
    12. Two shared_ptrs made from one raw pointer
    13. Using a unique_ptr after moving from it
    14. Try it yourself

    Module 2 · Memory

    2.6Smart pointers: unique_ptr and shared_ptr

    Let std::unique_ptr and std::shared_ptr delete heap objects for you. Hand over ownership with std::move, count owners with use_count, and break cycles with std::weak_ptr.

    About 25 minutesIntermediate

    On this page
    1. Key terms
    2. In 30 seconds
    3. std::unique_ptr: one owner
    4. A unique_ptr can’t be copied
    5. Handing over ownership with std::move
    6. std::shared_ptr: shared ownership
    7. Cycles and std::weak_ptr
    8. Raw pointers and references don’t own
    9. Which one should I use?
    10. Under the hood
    11. Common pitfalls
    12. Two shared_ptrs made from one raw pointer
    13. Using a unique_ptr after moving from it
    14. Try it yourself

    Key terms

    smart pointer
    An object that holds a pointer and deletes what it points to when it's destroyed. It's RAII for one heap object.
    owner
    The part of the program responsible for deleting an object. A smart pointer is an owner; a raw pointer or a reference is not.
    std::unique_ptr<T>
    A smart pointer with exactly one owner. It can't be copied, only moved.
    std::make_unique<T>(…)
    Creates a T on the heap from the arguments and returns a std::unique_ptr<T> that owns it.
    std::move
    Marks an object as something whose contents may be taken. Passing a unique_ptr through it hands over ownership. Module 4 covers moving in full.
    moved-from
    The state of an object after its contents were taken. A moved-from unique_ptr is empty: it holds nullptr.
    std::shared_ptr<T>
    A smart pointer that can be copied. All the copies share the object, and the last one to go deletes it.
    std::make_shared<T>(…)
    Creates a T and its control block in one heap allocation and returns a std::shared_ptr<T>.
    control block
    A small heap record that shared_ptrs share. It holds the count of owners.
    use_count()
    The number of shared_ptrs that currently own the object.
    cycle
    Objects that own each other, directly or through others. With shared_ptr, a cycle never reaches a count of 0, so it leaks.
    std::weak_ptr<T>
    A pointer to an object owned by shared_ptrs that doesn't count as an owner. lock() gives you a shared_ptr if the object still exists.
    non-owning
    Used to reach an object, never to delete it. Raw pointers (T*) and references (T&) are non-owning.

    In the last lesson, RAII made heap memory free itself: a destructor did the delete. Writing a class like that for every type you put on the heap would be tedious, so the standard library has ready-made ones, called smart pointers. std::unique_ptr is for an object with one owner, and std::shared_ptr is for an object that several parts of a program keep alive together.

    In 30 seconds

    • auto p = std::make_unique<T>(…) creates a T on the heap. The std::unique_ptr deletes it when p goes out of scope.
    • A unique_ptr can’t be copied, so there’s always exactly one owner. std::move hands ownership to another unique_ptr and leaves the first one empty.
    • std::make_shared<T>(…) returns a std::shared_ptr that can be copied. It counts its owners (use_count()), and the last one deletes the object.
    • Raw pointers and references are for using an object someone else owns. Two objects that own each other through shared_ptrs leak; make one of the links a std::weak_ptr.

    std::unique_ptr: one owner

    std::make_unique<Sequence>("chr1", "ACGT") (from <memory>) creates a Sequence on the heap from those values and returns a std::unique_ptr<Sequence> that owns it. You use it like a pointer: -> reaches a member, and * gives the object. When the unique_ptr is destroyed, it deletes the object.

    #include <memory>
    #include <print>
    #include <string>
    
    struct Sequence {
        std::string name;
        std::string bases;
        ~Sequence() { std::println("freeing {}", name); }
    };
    
    int main() {
        {
            auto seq = std::make_unique<Sequence>("chr1", "ACGT");
            std::println("{}: {} bases", seq->name, seq->bases.size());
        }
        std::println("after the block");
    }

    Output

    chr1: 4 bases
    freeing chr1
    after the block

    The destructor runs at the closing brace, with no delete anywhere. auto here means std::unique_ptr<Sequence>.

    A unique_ptr can’t be copied

    If you could copy a unique_ptr, two of them would delete the same object: a double free. So copying is forbidden. The standard library marks its copy constructor, the constructor that makes a copy, as deleted: it’s declared but can’t be used, and trying to use it is a compile error:

    #include <memory>
    
    auto first = std::make_unique<int>(42);
    auto second = first;

    The compiler rejects this

    main.cpp: In function ‘int main()’:
    main.cpp:4:15: error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = int; _Dp = std::default_delete<int>]’
        4 | auto second = first;
          |               ^~~~~
    In file included from /usr/include/c++/15/memory:80,
                     from main.cpp:1:
    /usr/include/c++/15/bits/unique_ptr.h:524:7: note: declared here
          |   unique_ptr(const unique_ptr&) = delete;
          |   ^~~~~~~~~~
    main.cpp:4:15: note: use ‘-fdiagnostics-all-candidates’ to display considered candidates
        4 | auto second = first;
          |               ^~~~~

    Handing over ownership with std::move

    You can still give the object to another owner. std::move(first) says “take what first holds”. The new unique_ptr takes the pointer, and first is left empty, holding nullptr:

    #include <memory>
    #include <print>
    #include <utility>
    
    auto first = std::make_unique<int>(42);
    std::unique_ptr<int> second = std::move(first);
    std::println("first is empty: {}", first == nullptr);
    std::println("second holds {}", *second);

    Output

    first is empty: true
    second holds 42

    Still one owner, now a different one. After the move, *first would be a null pointer dereference, so don’t use a moved-from unique_ptr until you give it a new object. Module 4 explains moving in full.

    std::shared_ptr: shared ownership

    Sometimes no single part of the program is clearly the last to use an object: two readers share one reference genome, and either may finish first. std::make_shared returns a std::shared_ptr, which you can copy. Every copy is an owner. The shared_ptrs keep a count of owners, use_count(), and the last one to go deletes the object.

    #include <memory>
    #include <print>
    #include <string>
    
    struct Genome {
        std::string name;
        ~Genome() { std::println("freeing {}", name); }
    };
    
    int main() {
        std::shared_ptr<Genome> reader1 = std::make_shared<Genome>("hg38");
        std::println("owners: {}", reader1.use_count());
        {
            std::shared_ptr<Genome> reader2 = reader1; // a copy: a second owner
            std::println("owners: {}", reader1.use_count());
        }
        std::println("owners: {}", reader1.use_count());
        std::println("end of main");
    }

    Output

    owners: 1
    owners: 2
    owners: 1
    end of main
    freeing hg38

    When reader2 is destroyed, the count drops to 1 and the genome stays. When reader1 is destroyed at the end of main, the count reaches 0 and the genome is freed.

    Inside the block: two ownersOn the stack, reader1 and reader2 are both std::shared_ptr<Genome>, each with two pointers. Their object pointers point at the Genome named hg38 on the heap; their control pointers point at the control block just before it, which holds the owner count 2. make_shared put the control block and the Genome in one heap allocation.StackHeapreader1: std::shared_ptr<Genome>objectcontrolreader2: std::shared_ptr<Genome>objectcontrolone allocation from make_sharedowners: 2Genome hg38
    Inside the block: two owners. On the stack, reader1 and reader2 are both std::shared_ptr<Genome>, each with two pointers. Their object pointers point at the Genome named hg38 on the heap; their control pointers point at the control block just before it, which holds the owner count 2. make_shared put the control block and the Genome in one heap allocation.

    PerformanceSharing has a cost

    Every copy and every destruction of a shared_ptr updates the count, and the count is updated safely even when several threads share it, which takes extra work. A unique_ptr has no count, so it costs about the same as a raw pointer you delete by hand. Use shared_ptr only when ownership really is shared.

    Cycles and std::weak_ptr

    A shared_ptr frees its object when the count reaches 0. If two objects own each other, each keeps the other’s count at 1 or more, and neither is ever freed. Here a node owns the next node, and the next node owns the previous one:

    #include <memory>
    #include <print>
    #include <string>
    
    struct Node {
        std::string name;
        std::shared_ptr<Node> next;
        std::shared_ptr<Node> prev;
        ~Node() { std::println("freeing {}", name); }
    };
    
    void link_pair() {
        auto a = std::make_shared<Node>("a");
        auto b = std::make_shared<Node>("b");
        a->next = b;
        b->prev = a; // now a and b own each other
        std::println("owners of a: {}, of b: {}", a.use_count(), b.use_count());
    }
    
    int main() {
        link_pair();
        std::println("end of main");
    }

    This fails when it runs

    ERROR: LeakSanitizer: detected memory leaks
    
    Indirect leak of 80 byte(s) in 1 object(s) allocated from:
        #0 operator new(unsigned long)
           … 8 frames inside the standard library
        #9 link_pair() main.cpp:14
        #10 main main.cpp:21
    
    Indirect leak of 80 byte(s) in 1 object(s) allocated from:
        #0 operator new(unsigned long)
           … 8 frames inside the standard library
        #9 link_pair() main.cpp:13
        #10 main main.cpp:21
    
    SUMMARY: AddressSanitizer: 160 byte(s) leaked in 2 allocation(s).

    At the end of link_pair, the local a and b go away, and each count drops from 2 to 1. Neither “freeing” line is printed, and LeakSanitizer reports both nodes when the program exits.

    The fix is to make one direction non-owning. A std::weak_ptr points to an object owned by shared_ptrs without counting as an owner. To use the object, call lock(): it returns a shared_ptr that owns the object for as long as you hold it, or an empty one if the object is already gone.

    #include <memory>
    #include <print>
    #include <string>
    
    struct Node {
        std::string name;
        std::shared_ptr<Node> next; // owns the next node
        std::weak_ptr<Node> prev;   // only watches the previous one
        ~Node() { std::println("freeing {}", name); }
    };
    
    void link_pair() {
        auto a = std::make_shared<Node>("a");
        auto b = std::make_shared<Node>("b");
        a->next = b;
        b->prev = a;
        std::println("owners of a: {}, of b: {}", a.use_count(), b.use_count());
        if (std::shared_ptr<Node> before = b->prev.lock()) {
            std::println("before b: {}", before->name);
        }
    }
    
    int main() {
        link_pair();
        std::println("end of main");
    }

    Output

    owners of a: 1, of b: 2
    before b: a
    freeing a
    freeing b
    end of main

    Now a has one owner, the local variable. When it goes, a is freed, its next lets go of b, and b is freed too.

    Key ideaOwnership points one way

    Most data has a natural direction: a parent owns its children, a list owns its next node. Use shared_ptr or unique_ptr in that direction, and weak_ptr or a raw pointer for links back.

    Raw pointers and references don’t own

    Smart pointers are for owning. When a function only uses an object for a while, it shouldn’t care how the object is owned: take a reference, or a raw pointer if “no object” is a valid answer. .get() gives you the raw pointer inside a smart pointer without giving up ownership.

    #include <memory>
    #include <print>
    #include <string>
    
    struct Model {
        std::string name;
        int layers;
    };
    
    void describe(const Model& model) {
        std::println("{} has {} layers", model.name, model.layers);
    }
    
    void describe_if_any(const Model* model) {
        if (model == nullptr) {
            std::println("no model loaded");
            return;
        }
        describe(*model);
    }
    
    int main() {
        auto model = std::make_unique<Model>("tiny-net", 4);
        describe(*model);
        describe_if_any(model.get());
        describe_if_any(nullptr);
    }

    Output

    tiny-net has 4 layers
    tiny-net has 4 layers
    no model loaded

    describe works with any Model: on the heap, on the stack, or inside a vector. A raw pointer in modern code means “I use this, someone else owns it”. Never delete one.

    Which one should I use?

    How should this code hold the object?
    1. Can it be a plain local variable, a struct member or an element of a container?

      Yes

      Store it by value: T or std::vector<T>No pointer at all. Its scope frees it.

      No
    2. Does someone else own it, and you only use it for a while?

      Yes

      A reference T&, or a raw pointer T* if it can be missingNon-owning: never delete it.

      No
    3. Do several parts of the program keep it alive, with no clear last user?

      Yes

      std::shared_ptr<T> from std::make_sharedUse std::weak_ptr<T> for links back.

      No
    4. Otherwise: std::unique_ptr<T> from std::make_unique: one owner, no count to keep

    WhatWhenWhyHow
    std::unique_ptrOne owner, and the object must live on the heap: it’s big, its size is only known at run time, or it must outlive the scope that made it.Deletes the object automatically, costs about the same as a raw pointer, and can’t be copied by mistake.auto p = std::make_unique<T>(…);
    std::shared_ptrSeveral owners, and you can’t say which one finishes last.The last owner deletes the object.auto p = std::make_shared<T>(…);
    std::weak_ptrA link back to an object owned by shared_ptrs.Doesn’t keep the object alive, so it can’t form a cycle.std::weak_ptr<T> w = p; then w.lock()
    T& or T*A function uses an object that someone else owns.Works however the object is owned.void f(const T& x), or T* when it can be nullptr

    Rule of thumb: reach for std::unique_ptr first; switch to std::shared_ptr only when ownership really is shared, and pass plain references to functions that only use the object.

    Under the hood

    A unique_ptr holds only a raw pointer and adds a destructor, so on this platform it’s the same size as one. A shared_ptr holds two pointers: one to the object and one to the control block, the shared record that holds the count. GCC’s std::make_shared puts the control block and the object in a single heap allocation, which is why it’s faster than creating them separately.

    #include <memory>
    #include <print>
    
    std::println("raw pointer: {} bytes", sizeof(int*));
    std::println("unique_ptr: {} bytes", sizeof(std::unique_ptr<int>));
    std::println("shared_ptr: {} bytes", sizeof(std::shared_ptr<int>));

    Output

    raw pointer: 8 bytes
    unique_ptr: 8 bytes
    shared_ptr: 16 bytes

    The control block also counts weak_ptrs. When the last shared_ptr goes, the object is destroyed, but the control block stays until the last weak_ptr goes too, so lock() can still check it and see that the object is gone.

    Common pitfalls

    Two shared_ptrs made from one raw pointer

    Each shared_ptr made directly from a raw pointer starts its own control block with its own count. Make two from the same pointer and each thinks it’s the only owner, so both delete the object:

    #include <memory>
    
    int* raw = new int(5);
    std::shared_ptr<int> a(raw);
    std::shared_ptr<int> b(raw); // a second, separate count for the same int

    This fails when it runs

    ERROR: AddressSanitizer: attempting double-free on 0x… in thread T0:
        #0 operator delete(void*, unsigned long)
           … 5 frames inside the standard library
        #6 main main.cpp
    
    0x… is located 0 bytes inside of 4-byte region [0x…,0x…)
    freed by thread T0 here:
        #0 operator delete(void*, unsigned long)
           … 5 frames inside the standard library
        #6 main main.cpp
    
    previously allocated by thread T0 here:
        #0 operator new(unsigned long)
        #1 main main.cpp:3
    
    SUMMARY: AddressSanitizer: double-free main.cpp in main

    The fix is to create the object with std::make_shared and then copy the shared_ptr: auto a = std::make_shared<int>(5); auto b = a;. Copies share one control block. With make_shared and make_unique, you never write new at all.

    Using a unique_ptr after moving from it

    After auto second = std::move(first);, first holds nullptr. Reading through it is a null pointer dereference, which is undefined behavior. If code might run after a move, check first: if (first != nullptr). Better, don’t touch a variable after you’ve moved from it.

    Common pitfallDon't delete what a smart pointer owns

    .get() lends you the pointer; it doesn’t give you ownership. Calling delete on it frees the object while the smart pointer still owns it, and the smart pointer frees it again later.

    Try it yourself

    Try it yourself

    This program creates a Model with new and frees it with delete. Change it so a std::unique_ptr owns the model and there’s no new or delete left. Keep print_model as it is.

    #include <memory>
    #include <print>
    #include <string>
    
    struct Model {
        std::string name;
        int layers;
    };
    
    void print_model(const Model* model) {
        std::println("{}: {} layers", model->name, model->layers);
    }
    
    int main() {
        Model* loaded = new Model("tiny-net", 4);
        print_model(loaded);
        delete loaded;
    }

    Expected output

    tiny-net: 4 layers
    Show a hint

    Change the type of loaded to std::unique_ptr<Model> and create it with std::make_unique<Model>(…). Take the raw pointer for print_model with .get().

    Show a solution
    #include <memory>
    #include <print>
    #include <string>
    
    struct Model {
        std::string name;
        int layers;
    };
    
    void print_model(const Model* model) {
        std::println("{}: {} layers", model->name, model->layers);
    }
    
    int main() {
        auto loaded = std::make_unique<Model>("tiny-net", 4);
        print_model(loaded.get());
    }

    std::make_unique creates the Model and loaded owns it, so the Model is freed when main ends, with no delete. print_model only uses the model, so it keeps its const Model* parameter and gets the pointer from loaded.get().

    Saved in this browser only.