Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::enable_shared_from_this: sharing an object’s existing ownership

std::enable_shared_from_this lets an object obtain a shared_ptr that uses the same control block as its current owner.

Version: C++23

Syntax

template<class T>
class enable_shared_from_this {
public:
    std::shared_ptr<T> shared_from_this();
    std::shared_ptr<const T> shared_from_this() const;
    std::weak_ptr<T> weak_from_this() noexcept;
    std::weak_ptr<const T> weak_from_this() const noexcept;
};

A class T that publicly and unambiguously derives from std::enable_shared_from_this<T> in <memory> gains shared_from_this() and weak_from_this(). When the first suitable std::shared_ptr takes ownership, it initializes a hidden weak link; a later shared_from_this() creates an owner of the same object and control block.

Calling shared_from_this() before the object is managed by a compatible shared_ptr constructs from an empty weak_ptr and throws std::bad_weak_ptr. weak_from_this() is noexcept and can return an empty weak pointer, allowing ownership to be tested without extending the lifetime first.

Do not create std::shared_ptr<T>(this): that creates an independent control block and risks double deletion. Merely placing the object on the stack, using private or ambiguous inheritance, or creating a second independent owner does not establish the required link. Prefer std::make_shared<T>, then expose shared_from_this().

Examples

#include <iostream>
#include <memory>

struct Node : std::enable_shared_from_this<Node> {
    explicit Node(int value) : value(value) {}
    int value;
};

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

Result

1 2 7

std::enable_shared_from_this → 1 2 7

Sources