blob: 3976b7e9b2e22e98c8b1cb8bb71ab7e82e271686 [file] [log] [blame]
Phil Nashb2132022012-05-04 07:55:11 +01001/*
Phil Nashb2132022012-05-04 07:55:11 +01002 * 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 Nashb2132022012-05-04 07:55:11 +01007 */
8#ifndef TWOBLUECUBES_CATCH_PTR_HPP_INCLUDED
9#define TWOBLUECUBES_CATCH_PTR_HPP_INCLUDED
10
11#include "catch_common.h"
12
Phil Nashd0be9ed2012-05-15 08:02:36 +010013namespace Catch {
14
Phil Nashb2132022012-05-04 07:55:11 +010015 // 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 Nashd0be9ed2012-05-15 08:02:36 +010019 class Ptr {
Phil Nashb2132022012-05-04 07:55:11 +010020 public:
21 Ptr() : m_p( NULL ){}
22 Ptr( T* p ) : m_p( p ){
Phil Nash61756972012-07-28 20:37:07 +010023 if( m_p )
24 m_p->addRef();
Phil Nashb2132022012-05-04 07:55:11 +010025 }
26 Ptr( const Ptr& other ) : m_p( other.m_p ){
Phil Nash61756972012-07-28 20:37:07 +010027 if( m_p )
28 m_p->addRef();
Phil Nashb2132022012-05-04 07:55:11 +010029 }
30 ~Ptr(){
31 if( m_p )
32 m_p->release();
33 }
34 Ptr& operator = ( T* p ){
35 Ptr temp( p );
36 swap( temp );
37 return *this;
38 }
39 Ptr& operator = ( Ptr& other ){
40 Ptr temp( other );
41 swap( temp );
42 return *this;
43 }
44 void swap( Ptr& other ){
45 std::swap( m_p, other.m_p );
46 }
47
48 T* get(){
49 return m_p;
50 }
51 const T* get() const{
52 return m_p;
53 }
54
55 T& operator*(){
56 return *m_p;
57 }
58 const T& operator*() const{
59 return *m_p;
60 }
61
62 T* operator->(){
63 return m_p;
64 }
65 const T* operator->() const{
66 return m_p;
67 }
Phil Nash61756972012-07-28 20:37:07 +010068 bool operator !() const {
69 return m_p == NULL;
70 }
Phil Nashb2132022012-05-04 07:55:11 +010071
72 private:
73 T* m_p;
74 };
75
76 struct IShared : NonCopyable {
Phil Nasha695eb92012-08-13 07:46:10 +010077 virtual ~IShared();
Phil Nashb2132022012-05-04 07:55:11 +010078 virtual void addRef() = 0;
79 virtual void release() = 0;
80 };
81
82 template<typename T>
83 struct SharedImpl : T {
84
85 SharedImpl() : m_rc( 0 ){}
86
87 virtual void addRef(){
88 ++m_rc;
89 }
90 virtual void release(){
91 if( --m_rc == 0 )
92 delete this;
93 }
94
95 int m_rc;
96 };
97
98} // end namespace Catch
99
100#endif // TWOBLUECUBES_CATCH_PTR_HPP_INCLUDED