Abstract Ownership Models for Automatic Resource Management
By The Coding Gopher
Published: 2026-10-02
URL: https://thecodinggopher.substack.com/p/c-smart-pointers-explained
Smart pointers are object wrappers around raw pointers in C++ designed to automate memory management. By leveraging the stack lifecycle, they ensure that dynamically allocated heap memory is automatically deleted when it is no longer needed, eliminating memory leaks and dangling pointers.
The Foundational Principle: RAII
Smart pointers operate entirely on the concept of Resource Acquisition Is Initialization (RAII).
RAII (Resource Acquisition Is Initialization) is the most important programming idiom in modern C++. Despite its confusing name, the core concept is simple: bind the lifecycle of a resource to the lifetime of a local object. Instead of manually allocating and freeing resources, you wrap the resource inside a class. The resource is acquired in the constructor and automatically released in the destructor. Because C++ guarantees that stack-allocated objects are destroyed when they go out of scope, your resources are guaranteed to clean themselves up.
-
Acquisition: Heap memory is allocated during the initialization of the smart pointer object on the stack.
-
Tracking: The smart pointer is used throughout your application code exactly like a traditional raw pointer.
-
Release: When the smart pointer leaves its execution scope, its destructor is automatically called, safely running delete on the underlying heap memory.
Join a community of senior engineers. Subscribe and get FREE access to System Design deep dives.
The Three Core Ownership Models
Modern C++ defines three distinct smart pointer types based on how they track resource ownership:
1. std::uniqueptr (Strict Exclusive Ownership)
std::uniqueptr is a C++ smart pointer that provides strict, exclusive ownership of a dynamically allocated object. It automatically deletes the managed object and frees its memory when the pointer goes out of scope, preventing memory leaks without requiring manual delete calls.
-
The Concept: Exactly one pointer owns the allocated resource.
-
Rules: It cannot be copied. Attempting a copy results in a compiler error. Ownership can only be moved to a new pointer using std::move().
You cannot copy a std::unique_ptr. Its copy constructor and copy assignment operator are explicitly deleted to enforce strict, exclusive ownership of the managed resource. If copying were allowed, multiple smart pointers would point to the same memory, causing a "double delete" crash when they go out of scope.
Depending on what you are trying to achieve, you have three primary alternatives:
1. Transfer Ownership (Move)
If you do not need the original pointer anymore, you can move it using std::move. This transfers the resource to the new pointer and leaves the original pointer empty (nullptr).
std::unique_ptr<int> ptr1 = std::make_make_unique<int>(42);
// std::unique_ptr<int> ptr2 = ptr1; // ERROR: Compilation fails!
std::unique_ptr<int> ptr2 = std::move(ptr1); // OK: ptr1 is now null, ptr2 owns the
// memory
In C++, std::uniqueptr cannot be copied, but its ownership can be transferred to another std::uniqueptr using std::move.
Because a unique pointer maintains strict, exclusive ownership over its managed resource, any attempt to copy it will result in a compilation error. Using std::move casts the pointer into an rvalue, allowing the move constructor or move assignment operator to safely shift ownership.
You use std::move with std::uniqueptr to transfer exclusive ownership of a dynamically allocated resource from one pointer to another. Because std::uniqueptr enforces strict, single ownership of a resource, it cannot be copied. Attempting to copy it results in a compilation error.
2. Duplicate the Data (Deep Copy)
If you want two separate pointers managing two separate objects with the same data, you must manually allocate a new std::unique_ptr and copy the underlying value.
std::unique_ptr<int> ptr1 = std::make_unique<int>(42);
// Create a new unique_ptr by dereferencing and copying the value of the first
std::unique_ptr<int> ptr2 = std::make_unique<int>(*ptr1);
3. Switch to Shared Ownership
If you genuinely need multiple pointers to share ownership of the exact same instance in memory, you should use std::sharedptr instead of std::uniqueptr. You can easily convert an existing std::uniqueptr into a std::sharedptr:
std::unique_ptr<int> unique = std::make_unique<int>(42);
// Cast and transfer into a shared_ptr
std::shared_ptr<int> shared1 = std::move(unique);
std::shared_ptr<int> shared2 = shared1; // OK: Both now safely share the resource
-
Primary Use: Default option for local scope allocations and unique object structures.
2. std::sharedptr (Distributed Shared Ownership)
A shared pointer (std::sharedptr in C++) is a type of smart pointer that allows multiple pointers to share ownership of a single dynamically allocated object. It manages the lifetime of that object automatically through a technique called reference counting.
-
The Concept: Multiple pointers co-own the exact same resource.
-
Rules: It maintains an internal reference counter. Copying the pointer increases the count; destroying a pointer decreases it. The memory is deleted only when the counter drops to zero.
-
Primary Use: Shared data access configurations where object lifecycles are unpredictable.
A std::shared_ptr object and its managed resource are destroyed when the reference count drops to zero. This happens automatically when the last remaining shared pointer instance goes out of scope, is reassigned a new value, or has its reset() method called.
3. std::weakptr (Non-Owning Reference)
In C++, std::weakptr is a smart pointer that holds a non-owning (”weak”) reference to an object managed by a std::shared_ptr. Unlike a shared pointer, a weak pointer does not increase the strong reference count of the object. This means it does not affect the object’s lifetime or prevent it from being destroyed. Its primary purpose is to safely observe an object without owning it.
-
Rules: It does not affect the reference counter. To safely access the data, it must be temporarily converted into a std::shared_ptr using .lock() to verify the resource still exists.
-
Primary Use: Breaking circular dependencies that would otherwise cause permanent memory locks.
Build Redis, Git, Docker & Claude Code From Scratch
Want to become a better software engineer?
Trusted by engineers at Google, NVIDIA, and Anthropic, CodeCrafters helps you rebuild technologies like Redis, Git, Docker, and Claude Code from scratch so you can deeply understand how real systems work.
We’ve partnered with CodeCrafters to give all readers an exclusive 40% lifetime discount.
💡 Engineers may expense platforms like this through their team’s learning budget.
Start Building & Unlock 40% Off
Visual Comparison
C++ smart pointers manage heap memory with distinct ownership models: a std::uniqueptr gives one single owner exclusive control over a resource and cannot be copied, a std::sharedptr allows multiple pointers to share ownership using a reference count that deletes the object when it hits zero, and a std::weak_ptracts as a non-owning observer to a shared pointer without changing its reference count, mainly used to stop circular loops.
unique_ptr ──► [ Heap Object ] (Only 1 pointer allowed)
shared_ptr ──┐
├──► [ Heap Object ] (Ref Count = 2)
shared_ptr ──┘
weak_ptr - - - ► [ Heap Object ] (Observes, does not increase count)
Clean Code Summary
#include <memory>
void example() {
// 1. Create a unique pointer (Preferred style using make_unique)
std::unique_ptr<int> unique = std::make_unique<int>(10);
// 2. Create a shared pointer
std::shared_ptr<int> shared1 = std::make_shared<int>(20);
std::shared_ptr<int> shared2 = shared1; // Ref count is now 2
// 3. Create a weak pointer observing the shared pointer
std::weak_ptr<int> weak = shared1; // Ref count stays at 2
} // unique and both shared pointers leave scope here. All memory is automatically freed!
Memory Layout Under the Hood
To understand the runtime cost of smart pointers, we must look at how they pack data in memory on 64-bit systems.
std::unique_ptr: Zero-Cost Footprint
A standard std::unique_ptr consumes exactly 8 bytes of stack space, making it identical in size to a raw pointer. It achieves this efficiency via the Empty Base Optimization (EBO).
When you do not provide a custom deleter, or provide a stateless one (like an empty struct or stateless lambda), the compiler optimizes its footprint to 0 bytes. If your custom deleter contains state (such as capturing values by value), the pointer size grows by the size of that state.
std::unique_ptr (No State Deleter):
+-----------------------+
| T* stored_ptr | -> Size: 8 bytes
+-----------------------+
std::shared_ptr: The Fat Pointer Layout
A std::shared_ptr is a fat pointer that occupies 16 bytes of stack space. It contains two separate 8-byte raw pointers:
-
A pointer directly targeting the managed heap object payload.
-
A pointer targeting a separate heap-allocated structures called the Control Block.
std::shared_ptr Layout:
+-----------------------+------------------------+
| T* ptr_to_object | ControlBlock* c_block | -> Size: 16 bytes
+-----------------------+------------------------+
| |
v v
+-----------------+ +---------------------------------------+
| Managed Object | | - Strong Ref Count (std::atomic) |
+-----------------+ | - Weak Ref Count (std::atomic) |
| - Custom Deleter / Allocator Functions|
+---------------------------------------+
| [](https://substackcdn.com/image/fetch/$s!tGuj!,fauto,qauto:good,flprogressive:steep/https%3A%2F%2Fsubstack-post-media.s3.amazonaws.com%2Fpublic%2Fimages%2Fe4a2a153-be6e-4551-992d-1a5830ca13a0708x504.png)In C++, a std::shared_ptr does not manage memory using a single pointer. Instead, it maintains a dual-pointer structureunder the hood: one pointer looks directly at the managed object, and the other points to a heap-allocated control block. |
|---|
Allocation Architecture: Factory Functions vs. Raw New
How you allocate smart pointers changes how your program interacts with the operating system allocator.
Allocation via Raw New
std::shared_ptr<Widget> ptr(new Widget());
This pattern triggers two distinct heap allocations. The runtime first hits the system allocator to build the Widget payload. It then immediately hits the allocator a second time to build the remote control block. This results in fragmented memory placement and decreased CPU cache locality.
Optimization via std::make_shared
auto ptr = std::make_shared<Widget>();
This requests one single contiguous chunk of heap memory from the operating system. The allocator places the reference tracking counters and the target payload back-to-back inside a single block.
[ Single Contiguous Heap Space Allocation via make_shared ]
+-----------------------------------+--------------------+
| Control Block (Strong, Weak Refs) | Managed Object T |
+-----------------------------------+--------------------+
-
The Caveat: Contiguous packing yields faster cache reads. However, the entire block of memory cannot be returned to the OS until both the strong reference count and the weak reference count drop to zero. If a long-lived std::weak_ptr observes the object, the payload memory space remains blocked even after the object’s destructor has executed.
Thread Safety Guarantees
Smart pointers offer specific hardware-level atomic guarantees, but they do not make application data inherently thread-safe.
-
What Is Safe: Reference counters inside the control block use lock-free CPU atomic instructions. Multiple concurrent threads can safely copy, pass, or destroy distinct instances of a std::shared_ptr that point to the same object without data races.
-
What Is Unsafe: Modifying the same instance of a smart pointer from two separate threads simultaneously creates an immediate data race. Additionally, smart pointers do not guard the underlying object data payload. If multiple threads execute mutating operations on the managed object, you must implement your own synchronization using primitives like std::mutex.
Advanced Lifecycle Management Tools
Custom Deleters
Smart pointers can manage custom non-memory system resources, such as closing file handles or breaking socket links automatically when a scope resolves.
void close_file(FILE* fp) { if (fp) std::fclose(fp); }
void process_logs() {
// Binds a custom deleter to close a file descriptor automatically
std::unique_ptr<FILE, decltype(&close_file)> filePtr(std::fopen("log.txt", "w"), &close_file);
}
Safe Self-Reference via std::enablesharedfrom_this
When an object managed by a std::sharedptr needs to pass a reference of itself to an external callback, returning the raw this pointer creates a duplicate control block, causing a fatal double-free crash. To resolve this, inherit from std::enablesharedfromthis:
class NetworkSession : public std::enable_shared_from_this<NetworkSession> {
public:
void dispatch() {
// Looks up the existing control block and safely increments the true counter
std::shared_ptr<NetworkSession> safe_self = shared_from_this();
register_worker(safe_self);
}
};
Join a community of senior engineers. Subscribe and get FREE access to System Design deep dives.
Thanks for reading! This post is public so feel free to share it.

