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

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

Er. Manoj Kumar — AuthorEr. Manoj Kumar•Last Updated: 26 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 Command Prompt Execution OutputWindows 11 Verified
    ⊞Administrator: Windows 11 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>#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?