In C++, when you create a class that derives from std::enable_shared_from_this
, it becomes eligible for special treatment by shared_ptr
, allowing the shared_from_this()
method to return a shared_ptr
to the object. However, certain conditions and constraints must be met, and this functionality is enabled through a mechanism involving a secret weak pointer called weak_this
.
Inside STL: The shared_ptr constructor and enable_shared_from_this
By Raymond Chen
From the article:
If you create a class of the form
struct S : std::enable_shared_from_this<S> { /* ... */ };
which derives from std::enable_shared_from_this of itself (using the curiously recurring template pattern), then this class becomes a candidate for special treatment by shared_ptr: The shared_from_this() method will produce a shared_ptr<S>. Some restrictions apply.
Add a Comment
Comments are closed.