Home > Backend Development > C++ > How Does `enable_shared_from_this` Solve Shared Pointer Ownership Issues in C ?

How Does `enable_shared_from_this` Solve Shared Pointer Ownership Issues in C ?

Patricia Arquette
Release: 2024-12-15 04:52:34
Original
683 people have browsed it

How Does `enable_shared_from_this` Solve Shared Pointer Ownership Issues in C  ?

How Does enable_shared_from_this Help in Maintaining Object Ownership?

While exploring Boost.Asio examples, you may have encountered enable_shared_from_this. Despite referencing the documentation, its usage remains unclear. Here's a comprehensive explanation and an example to clarify its purpose.

enable_shared_from_this allows you to create a valid shared_ptr instance for the object when you only have access to the object itself (represented by this). Without it, obtaining a shared_ptr for this would be impossible unless it was already defined as a member.

Consider the following example:

class Y: public enable_shared_from_this<Y>
{
public:

    shared_ptr<Y> f()
    {
        return shared_from_this();
    }
};
Copy after login

Here, method f() can return a valid shared_ptr, even though it lacks a member instance. Note that the following approach would fail:

class Y: public enable_shared_from_this<Y>
{
public:

    shared_ptr<Y> f()
    {
        return shared_ptr<Y>(this);
    }
};
Copy after login

The result would be two shared_ptrs with different reference counts. When the object is deleted, one of them will become a dangling reference.

It's important to note that enable_shared_from_this is now part of the C 11 standard, making it accessible from there as well as from Boost.

The above is the detailed content of How Does `enable_shared_from_this` Solve Shared Pointer Ownership Issues in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template