C++ Programming 11. Additional C++ Topics Added 8 mins read 19,650 views

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

Smart pointers in `` are RAII template classes that manage dynamic heap objects. std::unique_ptr provides exclusive zero-overhead ownership (cannot be copied, o...
Published: Nov 1, 2026Last Updated: Nov 21, 2026Curriculum: Class 12 / AP Physics / JEE-NEETReviewed by: OperateTools Editorial Board
Quick Summary & Direct Answer (AEO / GEO Extraction)

What is Smart Pointers in C++: unique_ptr, shared_ptr, and weak_ptr? Smart pointers in `` are RAII template classes that manage dynamic heap objects. std::unique_ptr provides exclusive zero-overhead ownership (cannot be copied, o...

Audience & Scope: Students, educators, and candidates preparing for academic examinations and technical assessments in C++ Programming.
How do std::unique_ptr, std::shared_ptr, and std::weak_ptr automate memory management and prevent memory leaks in modern C++?
Smart pointers in `<memory>` are RAII template classes that manage dynamic heap objects. std::unique_ptr provides exclusive zero-overhead ownership (cannot be copied, only moved). std::shared_ptr provides reference-counted shared ownership. std::weak_ptr provides a non-owning observer to break circular reference cycles in shared_ptr hierarchies.

Explanation & In-Depth Details

1. Smart Pointer Comparison:
```text
┌─────────────────┬──────────────────────┬──────────────────────┬─────────────────────────┐
│ Smart Pointer │ Ownership Model │ Overhead │ Copy / Move Ability │
├─────────────────┼──────────────────────┼──────────────────────┼─────────────────────────┤
│ std::unique_ptr │ Exclusive Single │ 0 bytes (Same as raw)│ Move-Only (No copy) │
│ std::shared_ptr │ Shared Ref-Counted │ 16-24 bytes (Control)│ Copyable & Moveable │
│ std::weak_ptr │ Non-owning Observer │ Control Block Pointer│ Breaks circular cycles │
└─────────────────┴──────────────────────┴──────────────────────┴─────────────────────────┘
```

2. Circular Reference Prevention:
Two `shared_ptr` objects referencing each other create a reference count that never drops to 0. Replacing one side with `std::weak_ptr` resolves the leak.

Code Example

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

class Resource {
public:
    std::string name;
    explicit Resource(std::string n) : name(std::move(n)) {
        std::cout << "[Constructed] Resource: " << name << "\n";
    }
    ~Resource() {
        std::cout << "[Destroyed] Resource: " << name << "\n";
    }
};

int main() {
    // 1. std::unique_ptr (Exclusive Ownership)
    std::cout << "--- unique_ptr Demo ---\n";
    {
        auto uPtr = std::make_unique<Resource>("Unique-01");
        // auto uCopy = uPtr; // COMPILE ERROR: Cannot copy unique_ptr!
        auto uMoved = std::move(uPtr); // Ownership transferred
    } // Destroyed here

    // 2. std::shared_ptr and std::weak_ptr
    std::cout << "\n--- shared_ptr & weak_ptr Demo ---\n";
    std::weak_ptr<Resource> observer;
    {
        auto sPtr1 = std::make_shared<Resource>("Shared-02");
        observer = sPtr1;
        std::cout << "Shared use count: " << sPtr1.use_count() << "\n";
        {
            auto sPtr2 = sPtr1; // Ref count = 2
            std::cout << "Shared use count in inner scope: " << sPtr1.use_count() << "\n";
        } // sPtr2 leaves scope, Ref count = 1
        std::cout << "Shared use count after inner scope: " << sPtr1.use_count() << "\n";
    } // sPtr1 leaves scope, Ref count = 0 -> Resource destroyed

    std::cout << "Is observed object expired? " << (observer.expired() ? "YES" : "NO") << "\n";
    return 0;
}

Interview Question & Tips

Q: Why should you use `std::make_unique` and `std::make_shared` instead of `new`?
A: `std::make_unique` is exception-safe and prevents leaks during argument evaluation. `std::make_shared` allocates the control block and object in a single contiguous memory allocation, improving cache locality.

Q: How does `std::weak_ptr` access its underlying object?
A: It must be converted to a `std::shared_ptr` using `.lock()` to verify the object still exists before dereferencing.

Best Practices

• Prefer `std::unique_ptr` by default; upgrade to `std::shared_ptr` only when multiple entities genuinely share ownership.
• Always use `std::make_unique` and `std::make_shared` instead of raw `new`.
• Use `std::weak_ptr` for observer patterns and tree parent/sibling pointers to prevent circular dependency memory leaks.
Academic Standards & Verified Citations

This study reference for Smart Pointers in C++: unique_ptr, shared_ptr, and weak_ptr is curated and verified against recognized curriculum benchmarks, peer-reviewed textbooks, and official technical documentation:

C++ Programming