diff options
Diffstat (limited to 'src/sharedcore.h')
| -rw-r--r-- | src/sharedcore.h | 101 |
1 files changed, 101 insertions, 0 deletions
diff --git a/src/sharedcore.h b/src/sharedcore.h new file mode 100644 index 0000000..9f42345 --- /dev/null +++ b/src/sharedcore.h | |||
| @@ -0,0 +1,101 @@ | |||
| 1 | /* | ||
| 2 | * Copyright (C) 2007-2008 Xagasoft, All rights reserved. | ||
| 3 | * | ||
| 4 | * This file is part of the libbu++ library and is released under the | ||
| 5 | * terms of the license contained in the file LICENSE. | ||
| 6 | */ | ||
| 7 | |||
| 8 | #ifndef BU_SHARED_CORE_H | ||
| 9 | #define BU_SHARED_CORE_H | ||
| 10 | |||
| 11 | #include "bu/util.h" | ||
| 12 | #include "bu/sio.h" | ||
| 13 | |||
| 14 | namespace Bu | ||
| 15 | { | ||
| 16 | template<typename Core> | ||
| 17 | class SharedCore | ||
| 18 | { | ||
| 19 | typedef class SharedCore<Core> _SharedType; | ||
| 20 | public: | ||
| 21 | SharedCore() : | ||
| 22 | data( new Core ), | ||
| 23 | iRefCount( new int(1) ) | ||
| 24 | { | ||
| 25 | } | ||
| 26 | |||
| 27 | SharedCore( const _SharedType &rSrc ) : | ||
| 28 | data( NULL ), | ||
| 29 | iRefCount( NULL ) | ||
| 30 | { | ||
| 31 | _softCopy( rSrc ); | ||
| 32 | } | ||
| 33 | |||
| 34 | virtual ~SharedCore() | ||
| 35 | { | ||
| 36 | _deref(); | ||
| 37 | } | ||
| 38 | |||
| 39 | SharedCore &operator=( const SharedCore &rhs ) | ||
| 40 | { | ||
| 41 | _softCopy( rhs ); | ||
| 42 | return *this; | ||
| 43 | } | ||
| 44 | |||
| 45 | int getRefCount() const | ||
| 46 | { | ||
| 47 | return *iRefCount; | ||
| 48 | } | ||
| 49 | |||
| 50 | protected: | ||
| 51 | Core *data; | ||
| 52 | void _hardCopy() | ||
| 53 | { | ||
| 54 | if( !data || !iRefCount ) | ||
| 55 | return; | ||
| 56 | sio << "_hardCopy()" << sio.nl; | ||
| 57 | Core *copy = new Core( *data ); | ||
| 58 | _deref(); | ||
| 59 | data = copy; | ||
| 60 | iRefCount = new int( 1 ); | ||
| 61 | } | ||
| 62 | |||
| 63 | private: | ||
| 64 | void _deref() | ||
| 65 | { | ||
| 66 | sio << "_deref()" << sio.nl; | ||
| 67 | if( (--(*iRefCount)) == 0 ) | ||
| 68 | { | ||
| 69 | sio << " --> iRefCount == 0, cleaning up." << sio.nl; | ||
| 70 | delete data; | ||
| 71 | delete iRefCount; | ||
| 72 | } | ||
| 73 | else | ||
| 74 | sio << " --> iRefCount == " << *iRefCount << sio.nl; | ||
| 75 | data = NULL; | ||
| 76 | iRefCount = NULL; | ||
| 77 | } | ||
| 78 | |||
| 79 | void _incRefCount() | ||
| 80 | { | ||
| 81 | sio << "_incRefCount()" << sio.nl; | ||
| 82 | if( iRefCount && data ) | ||
| 83 | ++(*iRefCount); | ||
| 84 | sio << " --> iRefCount == " << *iRefCount << sio.nl; | ||
| 85 | } | ||
| 86 | |||
| 87 | void _softCopy( const _SharedType &rSrc ) | ||
| 88 | { | ||
| 89 | sio << "_softCopy()" << sio.nl; | ||
| 90 | if( data ) | ||
| 91 | _deref(); | ||
| 92 | data = rSrc.data; | ||
| 93 | iRefCount = rSrc.iRefCount; | ||
| 94 | _incRefCount(); | ||
| 95 | } | ||
| 96 | |||
| 97 | int *iRefCount; | ||
| 98 | }; | ||
| 99 | }; | ||
| 100 | |||
| 101 | #endif | ||
