Namespaces
Variants
Views
Actions

Difference between revisions of "cpp/memory/enable shared from this"

From cppreference.com
< cpp‎ | memory
m (Update links.)
(Added LWG issue #2179 DR.)
 
(41 intermediate revisions by 26 users not shown)
Line 1: Line 1:
 
{{cpp/title|enable_shared_from_this}}
 
{{cpp/title|enable_shared_from_this}}
 
{{cpp/memory/enable_shared_from_this/navbar}}
 
{{cpp/memory/enable_shared_from_this/navbar}}
{{ddcl | header=memory | notes={{mark since c++11}} | 1=
+
{{ddcl|header=memory|since=c++11|
template< class T > class enable_shared_from_this;
+
template< class T >
 +
class enable_shared_from_this;
 
}}
 
}}
  
{{tt|std::enable_shared_from_this}} allows an object {{tt|t}} that is currently managed by a {{lc|std::shared_ptr}} named {{tt|pt}} to safely generate additional {{lc|std::shared_ptr}} instances {{tt|pt1, pt2, ...}} that all share ownership of {{tt|t}} with {{tt|pt}}.
+
{{tt|std::enable_shared_from_this}} allows an object {{c|t}} that is currently managed by a {{lc|std::shared_ptr}} named {{c|pt}} to safely generate additional {{lc|std::shared_ptr}} instances {{c|pt1}}, {{c|pt2}} etc. that all share ownership of {{c|t}} with {{c|pt}}.
  
Inheriting from {{tt|std::enable_shared_from_this<T>}} provides a type {{tt|T}} with a member function {{tt|shared_from_this}}.  If an object {{tt|t}} of type {{tt|T}} is managed by a {{c|std::shared_ptr<T>}} named {{tt|pt}}, then calling {{tt|T::shared_from_this}} will return a new {{c|std::shared_ptr<T>}} that shares ownership of {{tt|t}} with {{tt|pt}}.
+
Publicly inheriting from {{tt|std::enable_shared_from_this<T>}} provides the type {{tt|T}} with a member function {{tt|shared_from_this}}.  If an object {{c|t}} of type {{tt|T}} is managed by a {{c/core|std::shared_ptr<T>}} named {{c|pt}}, then calling {{tt|T::shared_from_this}} will return a new {{c/core|std::shared_ptr<T>}} that shares ownership of {{c|t}} with {{c|pt}}.
  
Note that prior to calling {{tt|shared_from_this}} on an object {{tt|t}}, there must be a {{lc|std::shared_ptr}} that owns {{tt|t}}.
+
===Data members===
 
+
{{dsc begin}}
Also note that {{tt|enable_shared_from_this}} provides an alternative to an expression like {{c|std::shared_ptr<T>(this)}}, which is likely to result in {{c|this}} being destructed more than once by multiple owners that are unaware of each other.
+
{{dsc hitem|Member|Description}}
 +
{{dsc expos mem obj|spec={{c/core|mutable std::weak_ptr<T>}}|weak_this|id=weak_this|the object tracking the control block of the first shared owner of {{c|*this}}}}
 +
{{dsc end}}
  
 
===Member functions===
 
===Member functions===
 
{{dsc begin}}
 
{{dsc begin}}
{{dsc prot mem ctor | cpp/memory/enable_shared_from_this/enable_shared_from_this | constructs an {{tt|enabled_shared_from_this}} object }}
+
{{dsc prot mem ctor|cpp/memory/enable_shared_from_this/enable_shared_from_this|constructs an {{tt|enable_shared_from_this}} object}}
{{dsc prot mem dtor | cpp/memory/enable_shared_from_this/~enable_shared_from_this | destroys an {{tt|enable_shared_from_this}} object }}
+
{{dsc prot mem dtor|cpp/memory/enable_shared_from_this/~enable_shared_from_this|destroys an {{tt|enable_shared_from_this}} object}}
{{dsc prot mem fun | cpp/memory/enable_shared_from_this/operator{{=}} | returns a reference to {{c|this}} }}
+
{{dsc prot mem fun|cpp/memory/enable_shared_from_this/operator{{=}}|returns a reference to {{c|*this}}}}
{{dsc mem fun | cpp/memory/enable_shared_from_this/shared_from_this | returns a {{c|shared_ptr}} which shares ownership of {{c|*this}} }}
+
{{dsc mem fun|cpp/memory/enable_shared_from_this/shared_from_this|returns a {{lc|std::shared_ptr}} which shares ownership of {{c|*this}}}}
 +
{{dsc mem fun|cpp/memory/enable_shared_from_this/weak_from_this|returns a {{lc|std::weak_ptr}} which shares ownership of {{c|*this}}|notes={{mark c++17}}}}
 
{{dsc end}}
 
{{dsc end}}
  
 
===Notes===
 
===Notes===
A common implementation for {{tt|enable_shared_from_this}} is to hold a weak reference (such as {{lc|std::weak_ptr}}) to {{c|this}}. The constructors of {{lc|std::shared_ptr}} can detect presence of a {{tt|enable_shared_from_this}} base and share ownership with the existing {{lc|std::shared_ptr}}s, instead of assuming the pointer is not managed by anyone else.
+
The constructors of {{lc|std::shared_ptr}} detect the presence of an unambiguous and accessible (i.e. public inheritance is mandatory) {{tt|enable_shared_from_this}} base and assign the newly created {{lc|std::shared_ptr}} to {{tti|weak_this}} if not already owned by a live {{lc|std::shared_ptr}}. Constructing a {{lc|std::shared_ptr}} for an object that is already managed by another {{lc|std::shared_ptr}} will not consult {{tti|weak_this}} and thus will lead to undefined behavior.
 +
 
 +
It is permitted to call {{tt|shared_from_this}} only on a previously shared object, i.e. on an object managed by {{c/core|std::shared_ptr<T>}}. Otherwise, {{lc|std::bad_weak_ptr}} is thrown (by the {{lc|std::shared_ptr}} constructor from a default-constructed {{tti|weak_this}}{{sep}}).
 +
 
 +
{{tt|enable_shared_from_this}} provides the safe alternative to an expression like {{c|std::shared_ptr<T>(this)}}, which is likely to result in {{c|this}} being destructed more than once by multiple owners that are unaware of each other (see example below).
  
 
===Example===
 
===Example===
 
{{example
 
{{example
|
+
|code=
| code=
+
#include <memory>
+
 
#include <iostream>
 
#include <iostream>
 +
#include <memory>
 +
 +
class Good : public std::enable_shared_from_this<Good>
 +
{
 +
public:
 +
    std::shared_ptr<Good> getptr()
 +
    {
 +
        return shared_from_this();
 +
    }
 +
};
  
struct Good: std::enable_shared_from_this<Good>
+
class Best : public std::enable_shared_from_this<Best>
 
{
 
{
     std::shared_ptr<Good> getptr() {
+
    struct Private{ explicit Private() = default; };
 +
   
 +
public:
 +
    // Constructor is only usable by this class
 +
    Best(Private) {}
 +
   
 +
    // Everyone else has to use this factory function
 +
    // Hence all Best objects will be contained in shared_ptr
 +
    static std::shared_ptr<Best> create()
 +
    {
 +
        return std::make_shared<Best>(Private());
 +
    }
 +
   
 +
     std::shared_ptr<Best> getptr()
 +
    {
 
         return shared_from_this();
 
         return shared_from_this();
 
     }
 
     }
 
};
 
};
  
struct Bad {
+
struct Bad
     std::shared_ptr<Bad> getptr() {
+
{
 +
     std::shared_ptr<Bad> getptr()
 +
    {
 
         return std::shared_ptr<Bad>(this);
 
         return std::shared_ptr<Bad>(this);
 
     }
 
     }
Line 45: Line 77:
 
};
 
};
  
int main()
+
void testGood()
 
{
 
{
 
     // Good: the two shared_ptr's share the same object
 
     // Good: the two shared_ptr's share the same object
     std::shared_ptr<Good> gp1(new Good);
+
     std::shared_ptr<Good> good0 = std::make_shared<Good>();
     std::shared_ptr<Good> gp2 = gp1->getptr();
+
     std::shared_ptr<Good> good1 = good0->getptr();
     std::cout << "gp2.use_count() = " << gp2.use_count() << '\n';
+
     std::cout << "good1.use_count() = " << good1.use_count() << '\n';
 +
}
  
     // Bad, each shared_ptr thinks it's the only owner of the object
+
void misuseGood()
     std::shared_ptr<Bad> bp1(new Bad);
+
{
     std::shared_ptr<Bad> bp2 = bp1->getptr();
+
    // Bad: shared_from_this is called without having std::shared_ptr owning the caller
     std::cout << "bp2.use_count() = " << bp2.use_count() << '\n';
+
    try
 +
    {
 +
        Good not_so_good;
 +
        std::shared_ptr<Good> gp1 = not_so_good.getptr();
 +
    }
 +
    catch (std::bad_weak_ptr& e)
 +
    {
 +
        // undefined behavior (until C++17) and std::bad_weak_ptr thrown (since C++17)
 +
        std::cout << e.what() << '\n';
 +
    }
 +
}
 +
 
 +
void testBest()
 +
{
 +
    // Best: Same but cannot stack-allocate it:
 +
    std::shared_ptr<Best> best0 = Best::create();
 +
    std::shared_ptr<Best> best1 = best0->getptr();
 +
    std::cout << "best1.use_count() = " << best1.use_count() << '\n';
 +
   
 +
    // Best stackBest; // <- Will not compile because Best::Best() is private.
 +
}
 +
 
 +
void testBad()
 +
{
 +
     // Bad, each shared_ptr thinks it is the only owner of the object
 +
     std::shared_ptr<Bad> bad0 = std::make_shared<Bad>();
 +
     std::shared_ptr<Bad> bad1 = bad0->getptr();
 +
     std::cout << "bad1.use_count() = " << bad1.use_count() << '\n';
 
} // UB: double-delete of Bad
 
} // UB: double-delete of Bad
| output=
+
 
gp2.use_count() = 2
+
int main()
bp2.use_count() = 1
+
{
 +
    testGood();
 +
    misuseGood();
 +
   
 +
    testBest();
 +
   
 +
    testBad();
 +
}
 +
|p=true
 +
|output=
 +
good1.use_count() = 2
 +
bad_weak_ptr
 +
best1.use_count() = 2
 +
bad1.use_count() = 1
 
Bad::~Bad() called
 
Bad::~Bad() called
 
Bad::~Bad() called
 
Bad::~Bad() called
*** glibc detected *** ./test: double free or corruption  
+
*** glibc detected *** ./test: double free or corruption
 
}}
 
}}
 +
 +
===Defect reports===
 +
{{dr list begin}}
 +
{{dr list item|wg=lwg|dr=2179|paper=P0033R1|std=C++11|before=given type {{tt|T}} derived from {{tt|enable_shared_from_this}}, the behavior of<br>constructing two {{c/core|std::shared_ptr<T>}}s from the same {{c/core|T*}} object was unclear|after=the behavior is<br>undefined in this case}}
 +
{{dr list item|wg=lwg|dr=2529|paper=P0033R1|std=C++11|before=it was unclear how the underlying {{lc|std::weak_ptr}} is updated|after=made clear}}
 +
{{dr list end}}
  
 
===See also===
 
===See also===
 
{{dsc begin}}
 
{{dsc begin}}
{{dsc inc | cpp/memory/dsc shared_ptr}}
+
{{dsc inc|cpp/memory/dsc shared_ptr}}
 +
{{dsc inc|cpp/memory/shared_ptr/dsc make_shared}}
 
{{dsc end}}
 
{{dsc end}}
  
[[de:cpp/memory/enable shared from this]]
+
{{langlinks|de|es|fr|it|ja|pt|ru|zh}}
[[es:cpp/memory/enable shared from this]]
+
[[fr:cpp/memory/enable shared from this]]
+
[[it:cpp/memory/enable shared from this]]
+
[[ja:cpp/memory/enable shared from this]]
+
[[pt:cpp/memory/enable shared from this]]
+
[[ru:cpp/memory/enable shared from this]]
+
[[zh:cpp/memory/enable shared from this]]
+

Latest revision as of 00:19, 22 October 2024

 
 
Utilities library
General utilities
Relational operators (deprecated in C++20)
 
Dynamic memory management
Uninitialized memory algorithms
Constrained uninitialized memory algorithms
Allocators
Garbage collection support
(C++11)(until C++23)
(C++11)(until C++23)
(C++11)(until C++23)
(C++11)(until C++23)
(C++11)(until C++23)
(C++11)(until C++23)



 
 
Defined in header <memory>
template< class T >
class enable_shared_from_this;
(since C++11)

std::enable_shared_from_this allows an object t that is currently managed by a std::shared_ptr named pt to safely generate additional std::shared_ptr instances pt1, pt2 etc. that all share ownership of t with pt.

Publicly inheriting from std::enable_shared_from_this<T> provides the type T with a member function shared_from_this. If an object t of type T is managed by a std::shared_ptr<T> named pt, then calling T::shared_from_this will return a new std::shared_ptr<T> that shares ownership of t with pt.

Contents

[edit] Data members

Member Description
mutable std::weak_ptr<T> weak_this the object tracking the control block of the first shared owner of *this
(exposition-only member object*)

[edit] Member functions

constructs an enable_shared_from_this object
(protected member function)
destroys an enable_shared_from_this object
(protected member function)
returns a reference to *this
(protected member function)
returns a std::shared_ptr which shares ownership of *this
(public member function)
returns a std::weak_ptr which shares ownership of *this
(public member function)

[edit] Notes

The constructors of std::shared_ptr detect the presence of an unambiguous and accessible (i.e. public inheritance is mandatory) enable_shared_from_this base and assign the newly created std::shared_ptr to weak_this if not already owned by a live std::shared_ptr. Constructing a std::shared_ptr for an object that is already managed by another std::shared_ptr will not consult weak_this and thus will lead to undefined behavior.

It is permitted to call shared_from_this only on a previously shared object, i.e. on an object managed by std::shared_ptr<T>. Otherwise, std::bad_weak_ptr is thrown (by the std::shared_ptr constructor from a default-constructed weak_this ).

enable_shared_from_this provides the safe alternative to an expression like std::shared_ptr<T>(this), which is likely to result in this being destructed more than once by multiple owners that are unaware of each other (see example below).

[edit] Example

#include <iostream>
#include <memory>
 
class Good : public std::enable_shared_from_this<Good>
{
public:
    std::shared_ptr<Good> getptr()
    {
        return shared_from_this();
    }
};
 
class Best : public std::enable_shared_from_this<Best>
{
    struct Private{ explicit Private() = default; };
 
public:
    // Constructor is only usable by this class
    Best(Private) {}
 
    // Everyone else has to use this factory function
    // Hence all Best objects will be contained in shared_ptr
    static std::shared_ptr<Best> create()
    {
        return std::make_shared<Best>(Private());
    }
 
    std::shared_ptr<Best> getptr()
    {
        return shared_from_this();
    }
};
 
struct Bad
{
    std::shared_ptr<Bad> getptr()
    {
        return std::shared_ptr<Bad>(this);
    }
    ~Bad() { std::cout << "Bad::~Bad() called\n"; }
};
 
void testGood()
{
    // Good: the two shared_ptr's share the same object
    std::shared_ptr<Good> good0 = std::make_shared<Good>();
    std::shared_ptr<Good> good1 = good0->getptr();
    std::cout << "good1.use_count() = " << good1.use_count() << '\n';
}
 
void misuseGood()
{
    // Bad: shared_from_this is called without having std::shared_ptr owning the caller
    try
    {
        Good not_so_good;
        std::shared_ptr<Good> gp1 = not_so_good.getptr();
    }
    catch (std::bad_weak_ptr& e)
    {
        // undefined behavior (until C++17) and std::bad_weak_ptr thrown (since C++17)
        std::cout << e.what() << '\n';
    }
}
 
void testBest()
{
    // Best: Same but cannot stack-allocate it:
    std::shared_ptr<Best> best0 = Best::create();
    std::shared_ptr<Best> best1 = best0->getptr();
    std::cout << "best1.use_count() = " << best1.use_count() << '\n';
 
    // Best stackBest; // <- Will not compile because Best::Best() is private.
}
 
void testBad()
{
    // Bad, each shared_ptr thinks it is the only owner of the object
    std::shared_ptr<Bad> bad0 = std::make_shared<Bad>();
    std::shared_ptr<Bad> bad1 = bad0->getptr();
    std::cout << "bad1.use_count() = " << bad1.use_count() << '\n';
} // UB: double-delete of Bad
 
int main()
{
    testGood();
    misuseGood();
 
    testBest();
 
    testBad();
}

Possible output:

good1.use_count() = 2
bad_weak_ptr
best1.use_count() = 2
bad1.use_count() = 1
Bad::~Bad() called
Bad::~Bad() called
*** glibc detected *** ./test: double free or corruption

[edit] Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
LWG 2179
(P0033R1)
C++11 given type T derived from enable_shared_from_this, the behavior of
constructing two std::shared_ptr<T>s from the same T* object was unclear
the behavior is
undefined in this case
LWG 2529
(P0033R1)
C++11 it was unclear how the underlying std::weak_ptr is updated made clear

[edit] See also

smart pointer with shared object ownership semantics
(class template) [edit]
creates a shared pointer that manages a new object
(function template) [edit]