Exploring std::make_shared: A Guide to Smart Pointers in C++

2025-09-15

In C++, std::make_shared is a clever utility function that creates and returns a std::shared_ptr. A std::shared_ptr is a smart pointer that manages the lifetime of an object. Unlike a raw pointer, it automatically deallocates the object when it's no longer needed, preventing memory leaks.

The main job of std::make_shared is to allocate the memory for the object and the shared pointer's control block (which contains the reference count) in a single allocation. This is a key advantage over doing it manually.

Let's look at the two ways to create a std::shared_ptr

Using new (The "old" way)

std::shared_ptr<MyObject> my_ptr = std::shared_ptr<MyObject>(new MyObject());

This method performs two separate memory allocations
one for the MyObject itself and another for the shared_ptr's control block. This can be less efficient and, as we'll see, can lead to a subtle bug.

Using std::make_shared (The "modern" way)

std::shared_ptr<MyObject> my_ptr = std::make_shared<MyObject>();

This is the preferred way! It performs only one memory allocation, which is more efficient and, importantly, safer.

As mentioned, std::make_shared avoids the double allocation of the object and the control block. This is a performance benefit, especially if you're creating many objects.

Problematic Code

void process(std::shared_ptr<MyObject> obj);

// This makes two allocations!
process(std::shared_ptr<MyObject>(new MyObject())); 

Preferred Alternative (with std::make_shared)

void process(std::shared_ptr<MyObject> obj);

// This makes only one allocation and is much safer!
process(std::make_shared<MyObject>()); 

This is a major reason to use std::make_shared. When you use new, it can lead to a memory leak if an exception is thrown in a very specific scenario.

The Scenario
Imagine a function call like this

process(std::shared_ptr<MyObject>(new MyObject()), some_other_function()); 

The order of execution isn't guaranteed. The compiler might

Call new MyObject().

Call some_other_function().

If some_other_function() throws an exception, the std::shared_ptr constructor is never called, and the memory allocated by new MyObject() is never freed.

Alternative (The Safe Way)
std::make_shared solves this by guaranteeing that the object and the shared_ptr are created atomically.

process(std::make_shared<MyObject>(), some_other_function()); 

In this case, the make_shared call is complete before some_other_function is even called, so there's no risk of a leak.

Sometimes an object needs to create a shared_ptr to itself. You might be tempted to do this

Problematic Code

class MyObject {
public:
    std::shared_ptr<MyObject> get_self_ptr() {
        return std::shared_ptr<MyObject>(this); // DANGER!
    }
};

This is a bad idea because it creates a new, separate shared_ptr with its own reference count. If you call this function multiple times, you'll get multiple shared_ptrs pointing to the same object, but with independent reference counts. This will lead to the object being deleted multiple times, causing a crash.

Preferred Alternative (Using enable_shared_from_this)
The correct way is to inherit from std::enable_shared_from_this.

#include <memory>

class MyObject : public std::enable_shared_from_this<MyObject> {
public:
    std::shared_ptr<MyObject> get_self_ptr() {
        return shared_from_this(); // This is the correct way!
    }
};

// Example usage:
auto obj_ptr = std::make_shared<MyObject>();
auto self_ptr = obj_ptr->get_self_ptr();

shared_from_this() returns a shared_ptr that is properly linked to the original object's control block, so they all share the same reference count.


cpp



C++ std::abs(float) Troubleshooting and Solutions

One of the most frequent issues developers face with std::abs(float) is function overload resolution. This happens when the compiler gets confused about which version of the abs function to use


Exploring C++ std::filesystem::recursive_directory_iterator Options

The std::filesystem::directory_options enum provides control over how directory iteration behaves. Using them helps you handle common situations gracefully


Optimizing C++ with Move Constructors: A Practical Guide

The Missing Move ConstructorA common mistake is forgetting to provide a move constructor. When a move constructor is not defined



A Developer's Guide to C++'s std::linear_congruential_engine::max and Distributions

The std::linear_congruential_engine::max() function is a member of the C++ standard library's numerics header. It's a key part of the linear congruential engine


Mastering C++ std::remainder: Pitfalls and Alternatives

The std::remainder function, found in the <cmath> header, calculates the remainder of a division operation, but unlike the % operator


Mastering std::ranges::chunk_view::begin in C++

std::ranges::chunk_view::begin is a function that returns an iterator pointing to the first element of a chunk_view. A chunk_view is a powerful tool in C++20 Ranges that breaks a range into subranges (or "chunks") of a specific size


Deduction Guides for C++23's std::ranges::zip_view: Pitfalls and Alternatives

Here's a friendly breakdown of the deduction guides for std::ranges::zip_view, common pitfalls, and some alternative approaches


C++ Utilities: A Deep Dive into FLT_EVAL_METHOD

FLT_EVAL_METHOD is a macro that tells the compiler how it should perform intermediate calculations on floating-point expressions


Title 2: Focused and Direct

std::mdspan and its empty() member function were added in C++23. If you're using an older version of the C++ standard (like C++17 or C++20), your compiler won't recognize it


Understanding and Replacing std::flush in C++

In C++, output streams like std::cout often buffer data. This means that instead of writing each character to the screen or a file immediately