Phil Nash | b213202 | 2012-05-04 07:55:11 +0100 | [diff] [blame] | 1 | /* |
Phil Nash | b213202 | 2012-05-04 07:55:11 +0100 | [diff] [blame] | 2 | * Created by Phil on 02/05/2012. |
| 3 | * Copyright 2012 Two Blue Cubes Ltd. All rights reserved. |
| 4 | * |
| 5 | * Distributed under the Boost Software License, Version 1.0. (See accompanying |
| 6 | * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) |
Phil Nash | b213202 | 2012-05-04 07:55:11 +0100 | [diff] [blame] | 7 | */ |
| 8 | #ifndef TWOBLUECUBES_CATCH_PTR_HPP_INCLUDED |
| 9 | #define TWOBLUECUBES_CATCH_PTR_HPP_INCLUDED |
| 10 | |
| 11 | #include "catch_common.h" |
| 12 | |
Phil Nash | d0be9ed | 2012-05-15 08:02:36 +0100 | [diff] [blame^] | 13 | namespace Catch { |
| 14 | |
Phil Nash | b213202 | 2012-05-04 07:55:11 +0100 | [diff] [blame] | 15 | // An intrusive reference counting smart pointer. |
| 16 | // T must implement addRef() and release() methods |
| 17 | // typically implementing the IShared interface |
| 18 | template<typename T> |
Phil Nash | d0be9ed | 2012-05-15 08:02:36 +0100 | [diff] [blame^] | 19 | class Ptr { |
Phil Nash | b213202 | 2012-05-04 07:55:11 +0100 | [diff] [blame] | 20 | public: |
| 21 | Ptr() : m_p( NULL ){} |
| 22 | Ptr( T* p ) : m_p( p ){ |
| 23 | m_p->addRef(); |
| 24 | } |
| 25 | Ptr( const Ptr& other ) : m_p( other.m_p ){ |
| 26 | m_p->addRef(); |
| 27 | } |
| 28 | ~Ptr(){ |
| 29 | if( m_p ) |
| 30 | m_p->release(); |
| 31 | } |
| 32 | Ptr& operator = ( T* p ){ |
| 33 | Ptr temp( p ); |
| 34 | swap( temp ); |
| 35 | return *this; |
| 36 | } |
| 37 | Ptr& operator = ( Ptr& other ){ |
| 38 | Ptr temp( other ); |
| 39 | swap( temp ); |
| 40 | return *this; |
| 41 | } |
| 42 | void swap( Ptr& other ){ |
| 43 | std::swap( m_p, other.m_p ); |
| 44 | } |
| 45 | |
| 46 | T* get(){ |
| 47 | return m_p; |
| 48 | } |
| 49 | const T* get() const{ |
| 50 | return m_p; |
| 51 | } |
| 52 | |
| 53 | T& operator*(){ |
| 54 | return *m_p; |
| 55 | } |
| 56 | const T& operator*() const{ |
| 57 | return *m_p; |
| 58 | } |
| 59 | |
| 60 | T* operator->(){ |
| 61 | return m_p; |
| 62 | } |
| 63 | const T* operator->() const{ |
| 64 | return m_p; |
| 65 | } |
| 66 | |
| 67 | private: |
| 68 | T* m_p; |
| 69 | }; |
| 70 | |
| 71 | struct IShared : NonCopyable { |
| 72 | virtual ~IShared(){} |
| 73 | virtual void addRef() = 0; |
| 74 | virtual void release() = 0; |
| 75 | }; |
| 76 | |
| 77 | template<typename T> |
| 78 | struct SharedImpl : T { |
| 79 | |
| 80 | SharedImpl() : m_rc( 0 ){} |
| 81 | |
| 82 | virtual void addRef(){ |
| 83 | ++m_rc; |
| 84 | } |
| 85 | virtual void release(){ |
| 86 | if( --m_rc == 0 ) |
| 87 | delete this; |
| 88 | } |
| 89 | |
| 90 | int m_rc; |
| 91 | }; |
| 92 | |
| 93 | } // end namespace Catch |
| 94 | |
| 95 | #endif // TWOBLUECUBES_CATCH_PTR_HPP_INCLUDED |