blob: 3ebe9f74920b3c664859d743d8a667fd34fad580 [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 ){
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