Unit 5: Standard Template Library (STL) & Advanced ConceptsLesson #20 / 20

Lesson 20: Modern C++ Smart Pointers: unique_ptr, shared_ptr & RAII

NSNextSemโ€ขLast Updated: 5 Aug, 2026

๐Ÿ’Ž Modern C++ (C++11/14/17/20) Smart Pointers

Raw pointers (new / delete) are prone to memory leaks and double-free bugs. Modern C++ solves memory safety using Smart Pointers declared in <memory>.


๐Ÿ›ก๏ธ Smart Pointer Types

  • ๐Ÿ”’ std::unique_ptr<T>: Sole, exclusive ownership. Zero overhead. Automatically deletes resource when going out of scope. Cannot be copied, only moved via std::move().
  • ๐Ÿ‘ฅ std::shared_ptr<T>: Shared ownership using reference counting. Resource is freed when the last shared_ptr owner is destroyed.
  • ๐Ÿ”— std::weak_ptr<T>: Non-owning observer reference to a shared_ptr to break circular dependency memory leaks.

  • ๐Ÿ’ป Code Example: std::makeunique & std::makeshared

    โŠžC++ Source Code (main.cpp)
    #include <iostream>
    #include <memory>
    class Widget {
    public:
    Widget() { std::cout << "๐Ÿ’Ž Widget Allocated on Heap" << std::endl; }
    ~Widget() { std::cout << "๐Ÿงน Widget Automatically Destructed (Zero Memory Leaks)" << std::endl; }
    void execute() { std::cout << "โšก Widget executing task..." << std::endl; }
    };
    int main() {
    // Modern C++ Memory Allocation (No explicit delete required!)
    std::unique_ptr<Widget> w1 = std::make_unique<Widget>();
    w1->execute();
    // Transfer ownership using std::move
    std::unique_ptr<Widget> w2 = std::move(w1);
    if (!w1) std::cout << "w1 is now null after std::move ownership transfer." << std::endl;
    return 0;
    } // w2 goes out of scope here -> Widget destructor fires automatically!
    โŠžWindows 11 Pro Terminal Execution OutputWindows 11 Pro Verified
    โŠžAdministrator: Windows 11 Pro Command Prompt (g++ GCC 13.2.0)
    โ€”โ–กโœ•

    Microsoft Windows [Version 10.0.22631.3007] (Windows 11 Pro x86_64)

    (c) Microsoft Corporation. All rights reserved.

    C:\Users\Student\CPP_Project>#include <iostream>

    C:\Users\Student\CPP_Project> g++ -o main.exe main.cpp C:\Users\Student\CPP_Project> main.exe Hello World from C++ on Windows 11 Pro! [Process exited with code 0 in 0.001 seconds]

    > โŠž Windows Tip: Modern C++ smart pointers make memory safety in Windows 11 enterprise C++ codebases automatic, clean, and bug-free!

    Interactive Knowledge Check

    Test your understanding of Lesson #20 concepts

    Which smart pointer represents EXCLUSIVE ownership of a Heap object and cannot be copied?