00001 /* Copyright 2010 Jukka Jylänki 00002 00003 Licensed under the Apache License, Version 2.0 (the "License"); 00004 you may not use this file except in compliance with the License. 00005 You may obtain a copy of the License at 00006 00007 http://www.apache.org/licenses/LICENSE-2.0 00008 00009 Unless required by applicable law or agreed to in writing, software 00010 distributed under the License is distributed on an "AS IS" BASIS, 00011 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 00012 See the License for the specific language governing permissions and 00013 limitations under the License. */ 00014 #pragma once 00015 00019 #include <malloc.h> 00020 #include <cstdlib> 00021 #include <cassert> 00022 00024 #define Ptr(type) kNet::SharedPtr< type > 00025 00026 namespace kNet 00027 { 00028 00030 class RefCountable 00031 { 00032 public: 00033 RefCountable():refCount(0) {} 00034 // ~RefCountable() {} // Can't put any functionality here since not virtual. 00035 00036 void AddRef() { ++refCount; } 00037 void DecRef() { assert(refCount > 0); --refCount; } 00038 unsigned int RefCount() { return refCount; } 00039 00040 private: 00041 unsigned int refCount; 00042 }; 00043 00049 template<typename T> 00050 class SharedPtr 00051 { 00052 public: 00054 SharedPtr():dataPtr(0) {} 00055 00057 SharedPtr(T *ptr); 00058 00060 SharedPtr(const SharedPtr<T> &rhs); 00061 00063 template<typename T2> 00064 SharedPtr(const SharedPtr<T2> &rhs); 00065 00067 SharedPtr<T> &operator=(const SharedPtr<T> &rhs); 00068 00070 SharedPtr<T> &operator=(T *ptr); 00071 00072 // Releases use of the object. 00073 ~SharedPtr(); 00074 00075 unsigned int RefCount() const; 00076 00077 const T *ptr() const; 00078 const T *operator->() const; 00079 const T &operator*() const; 00080 00081 operator T*(); 00082 00083 T *ptr(); 00084 T *operator->(); 00085 T &operator*(); 00086 00087 operator bool() const; 00088 00089 operator bool(); 00090 00091 private: 00092 T *dataPtr; 00093 00094 void AddRef(); 00095 void Release(); 00096 }; 00097 00102 template<typename T> 00103 bool operator==(const SharedPtr<T> &a, const SharedPtr<T> &b) 00104 { 00105 if (a.ptr() == b.ptr()) 00106 return true; 00107 else 00108 return false; 00109 } 00110 00111 } // ~kNet 00112 00113 #include "kNet/SharedPtr.inl" 00114
1.7.1