Modern C++ Smart Pointers: unique_ptr, shared_ptr & weak_ptr Deep Dive

In Modern C++ (C++11 and beyond), manual memory management with new and delete is considered an anti-pattern. Instead, modern software relies on Smart Pointers defined in the <memory> header to automate resource cleanup via RAII.

Modern C++ Smart Pointers Architecture unique_ptr shared_ptr weak_ptr
Figure 7: The Modern C++ Smart Pointer Hierarchy: Ownership Semantics & Control Blocks

1. std::unique_ptr<T> (Exclusive Ownership)

#include <iostream>
#include <memory>

class Sensor {
public:
    Sensor() { std::cout << "Sensor initialized\n"; }
    ~Sensor() { std::cout << "Sensor destroyed automatically!\n"; }
    void readData() { std::cout << "Reading telemetry...\n"; }
};

int main() {
    {
        // Safe creation: Zero raw new/delete
        auto s = std::make_unique<Sensor>();
        s->readData();
    } // Exiting block: Destructor automatically called here!

    return 0;
}

2. std::shared_ptr<T> and std::weak_ptr<T>

#include <iostream>
#include <memory>

int main() {
    // Shared ownership with reference counting
    auto p1 = std::make_shared<int>(500);
    std::cout << "Initial count: " << p1.use_count() << "\n"; // 1

    {
        auto p2 = p1; // Copy increments reference count
        std::cout << "Inside scope count: " << p1.use_count() << "\n"; // 2
    } // p2 destroyed, count decrements back to 1

    std::cout << "Outside scope count: " << p1.use_count() << "\n"; // 1
    return 0;
}

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. Why is std::unique_ptr preferred over std::shared_ptr by default?

std::unique_ptr provides zero-overhead exclusive ownership. It has the exact same memory footprint (8 bytes) and execution speed as a raw pointer. std::shared_ptr maintains an atomic reference count control block on the heap, adding memory and synchronization overhead.

Q2. Why should you use std::make_unique and std::make_shared instead of 'new'?

std::make_unique() is exception-safe (prevents memory leaks during argument evaluation) and cleaner. std::make_shared() performs a single combined heap allocation for both the control block and the object, improving CPU cache locality.

Explore Related C++ Tutorials & Next Steps

Boost your C++ proficiency by studying these closely connected core modules:

Raw Dynamic Memory

Understanding why raw new/delete is dangerous.

C++ RAII Idiom

How smart pointers wrap heap memory into stack scope.

Move Semantics

Transferring unique_ptr ownership with std::move.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!