1//// 2Copyright 2002, 2003, 2015, 2017, 2019 Peter Dimov 3 4Distributed under the Boost Software License, Version 1.0. 5 6See accompanying file LICENSE_1_0.txt or copy at 7http://www.boost.org/LICENSE_1_0.txt 8//// 9 10[#enable_shared_from] 11# enable_shared_from 12:toc: 13:toc-title: 14:idprefix: enable_shared_from_ 15 16## Description 17 18`enable_shared_from` is used as a base class that allows a `shared_ptr` or a 19`weak_ptr` to be obtained given a raw pointer to the object, by using the 20functions `shared_from` and `weak_from`. 21 22`enable_shared_from` differs from `enable_shared_from_this<T>` by the fact 23that it's not a template, and is its recommended replacement for new code. 24 25## Example 26 27``` 28#include <boost/smart_ptr/enable_shared_from.hpp> 29#include <boost/shared_ptr.hpp> 30#include <cassert> 31 32class Y: public boost::enable_shared_from 33{ 34public: 35 36 boost::shared_ptr<Y> f() 37 { 38 return boost::shared_from( this ); 39 } 40}; 41 42int main() 43{ 44 boost::shared_ptr<Y> p(new Y); 45 boost::shared_ptr<Y> q = p->f(); 46 assert(p == q); 47 assert(!(p < q || q < p)); // p and q must share ownership 48} 49``` 50 51## Synopsis 52 53`enable_shared_from` is defined in `<boost/smart_ptr/enable_shared_from.hpp>`. 54 55``` 56namespace boost { 57 58 class enable_shared_from: public enable_shared_from_this<enable_shared_from> 59 { 60 }; 61 62 template<class T> shared_ptr<T> shared_from( T * p ); 63 template<class T> weak_ptr<T> weak_from( T * p ) noexcept; 64} 65``` 66 67## Functions 68 69``` 70template<class T> shared_ptr<T> shared_from( T * p ); 71``` 72[none] 73* {blank} 74+ 75Returns:: `shared_ptr<T>( p\->enable_shared_from::shared_from_this(), p )`. 76 77NOTE: Throws `bad_weak_ptr` when `p` is not owned by a `shared_ptr`. 78 79``` 80template<class T> weak_ptr<T> weak_from( T * p ) noexcept; 81``` 82[none] 83* {blank} 84+ 85Returns:: `weak_ptr<T>( p\->enable_shared_from::weak_from_this(), p )`. 86 87NOTE: Unlike `shared_from(this)`, `weak_from(this)` is valid in a destructor 88 and returns a `weak_ptr` that is `expired()` but still shares ownership 89 with other `weak_ptr` instances (if any) that refer to the object. 90