00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00018 #ifndef LIBCWD_SMART_PTR_H
00019 #define LIBCWD_SMART_PTR_H
00020
00021 #ifndef LIBCWD_PRIVATE_STRUCT_TSD_H
00022 #include <libcwd/private_struct_TSD.h>
00023 #endif
00024
00025 namespace libcwd {
00026 namespace _private_ {
00027
00028 class refcnt_charptr_ct {
00029 private:
00030 int M_reference_count;
00031 char* M_ptr;
00032 public:
00033 refcnt_charptr_ct(char* ptr) : M_reference_count(1), M_ptr(ptr) { }
00034 void increment(void) { ++M_reference_count; }
00035 bool decrement(void)
00036 {
00037 if (M_ptr && --M_reference_count == 0)
00038 {
00039 delete [] M_ptr;
00040 M_ptr = NULL;
00041 return true;
00042 }
00043 return false;
00044 }
00045 char* get(void) const { return M_ptr; }
00046 int reference_count(void) const { return M_reference_count; }
00047 };
00048
00049 class smart_ptr {
00050 private:
00051 void* M_ptr;
00052 bool M_string_literal;
00053
00054 public:
00055
00056 smart_ptr(void) : M_ptr(NULL), M_string_literal(true) { }
00057 ~smart_ptr() { if (!M_string_literal) reinterpret_cast<refcnt_charptr_ct*>(M_ptr)->decrement(); }
00058
00059
00060 smart_ptr(smart_ptr const& ptr) : M_ptr(NULL), M_string_literal(true) { copy_from(ptr); }
00061
00062
00063 smart_ptr(char const* ptr) : M_string_literal(true) { copy_from(ptr); }
00064 smart_ptr(char* ptr) : M_string_literal(true) { copy_from(ptr); }
00065
00066 public:
00067
00068 smart_ptr& operator=(smart_ptr const& ptr) { copy_from(ptr); return *this; }
00069 smart_ptr& operator=(char const* ptr) { copy_from(ptr); return *this; }
00070 smart_ptr& operator=(char* ptr) { copy_from(ptr); return *this; }
00071
00072 public:
00073
00074 operator char const* (void) const { return get(); }
00075
00076
00077 bool operator==(smart_ptr const& ptr) const { return get() == ptr.get(); }
00078 bool operator==(char const* ptr) const { return get() == ptr; }
00079 bool operator!=(smart_ptr const& ptr) const { return get() != ptr.get(); }
00080 bool operator!=(char const* ptr) const { return get() != ptr; }
00081
00082 public:
00083 bool is_null(void) const { return M_ptr == NULL; }
00084 char const* get(void) const { return M_string_literal ? reinterpret_cast<char*>(M_ptr) : reinterpret_cast<refcnt_charptr_ct*>(M_ptr)->get(); }
00085
00086 protected:
00087
00088 void copy_from(smart_ptr const& ptr);
00089 void copy_from(char const* ptr);
00090 void copy_from(char* ptr);
00091
00092 private:
00093
00094 void increment(void) { if (!M_string_literal) reinterpret_cast<refcnt_charptr_ct*>(M_ptr)->increment(); }
00095 void decrement(LIBCWD_TSD_PARAM);
00096 };
00097
00098 }
00099 }
00100
00101 #endif // LIBCWD_SMART_PTR_H