Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::make_shared — creating an object with shared ownership

std::make_shared creates an object and returns a managing std::shared_ptr. For a non-array type, it forwards arguments to initialize the object. Copies of the pointer share the same object and responsibility for its lifetime.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <memory>

// Non-array overload in C++23:
template<class T, class... Args>
std::shared_ptr<T> make_shared(Args&&... args);

// Usage:
auto p = std::make_shared<T>(args...);

std::make_shared<T>(args...), declared in <memory>, creates an object and returns a std::shared_ptr<T>. For a non-array type, it directly initializes an object of type T using T(std::forward<Args>(args)...). In C++23, this does not necessarily call a constructor: it also supports scalar initialization and, where valid, parenthesized aggregate initialization. After a successful call, use_count() is 1. Array overloads also exist: for example, std::make_shared<int[]>(3) creates three elements with value 0.

Copying a std::shared_ptr shares the object rather than copying it. Destroying one copy decreases the owner count; the object is destroyed when the last owner releases ownership. In the example, second modifies the same Counter that first points to. After the inner block ends, the owner count drops from 2 to 1.

The standard recommends at most one allocation but does not guarantee it. If allocation or a constructor throws, no storage for the object being created is leaked. The function accepts no custom deleter. If initialization invokes a constructor, that constructor must be accessible from the library context, not just the call site.

This entry targets C++23. The linked document is an evolving working draft and may include later changes; the displayed syntax deliberately omits constexpr. A repository compiler flag does not attest to the production environment.

Examples

#include <iostream>
#include <memory>

struct Counter {
    int value;
    explicit Counter(int initial) : value(initial) {}
};

int main() {
    auto first = std::make_shared<Counter>(7);
    {
        auto second = first;
        ++second->value;
        std::cout << first->value << ' ' << first.use_count() << '\n';
    }
    std::cout << first->value << ' ' << first.use_count() << '\n';
}

Result

8 2
8 1

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources