1 //===----------------------------------------------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is dual licensed under the MIT and the University of Illinois Open 6 // Source Licenses. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 // template<class T> 11 // class enable_shared_from_this 12 // { 13 // protected: 14 // enable_shared_from_this(); 15 // enable_shared_from_this(enable_shared_from_this const&); 16 // enable_shared_from_this& operator=(enable_shared_from_this const&); 17 // ~enable_shared_from_this(); 18 // public: 19 // shared_ptr<T> shared_from_this(); 20 // shared_ptr<T const> shared_from_this() const; 21 // }; 22 23 #include <memory> 24 #include <cassert> 25 26 struct T 27 : public std::enable_shared_from_this<T> 28 { 29 }; 30 31 struct Y : T {}; 32 33 struct Z : Y {}; 34 35 int main() 36 { 37 { 38 std::shared_ptr<Y> p(new Z); 39 std::shared_ptr<T> q = p->shared_from_this(); 40 assert(p == q); 41 assert(!p.owner_before(q) && !q.owner_before(p)); // p and q share ownership 42 } 43 { 44 std::shared_ptr<Y> p = std::make_shared<Z>(); 45 std::shared_ptr<T> q = p->shared_from_this(); 46 assert(p == q); 47 assert(!p.owner_before(q) && !q.owner_before(p)); // p and q share ownership 48 } 49 } 50