00001 #ifndef SharedArray_H 00002 #define SharedArray_H 00003 00004 #include <QDebug> 00005 00006 // TODO: thread safe 00007 template<class T> struct SharedArray 00008 { 00009 SharedArray(); 00010 SharedArray(const SharedArray<T> &source); 00011 ~SharedArray(); 00012 00013 SharedArray& operator=(const SharedArray<T> &source); 00014 00015 void free(); 00016 void setSize(int size); 00017 int getSize(); 00018 00019 T* getData(); 00020 inline T& operator[](int i); 00021 inline const T& operator[](int i) const; 00022 00023 private: 00024 void set(const SharedArray<T> &source); 00025 00026 T *data; 00027 int size, *copyCount; 00028 }; 00029 00030 // ### SharedData ### 00031 00032 template<class T> SharedArray<T>::SharedArray() 00033 { 00034 data = 0; 00035 size = 0; 00036 copyCount = 0; 00037 } 00038 00039 template<class T> SharedArray<T>::SharedArray(const SharedArray<T> &source) 00040 { 00041 //qDebug() << "SharedData copy constructor"; 00042 set(source); 00043 } 00044 00045 template<class T> SharedArray<T>& SharedArray<T>::operator=(const SharedArray<T> &source) 00046 { 00047 //qDebug() << "SharedData assign"; 00048 free(); 00049 set(source); 00050 00051 return *this; 00052 } 00053 00054 template<class T> SharedArray<T>::~SharedArray() 00055 { 00056 free(); 00057 } 00058 00059 template<class T> void SharedArray<T>::free() 00060 { 00061 if(data != 0) 00062 { 00063 if((*copyCount) == 1) { 00064 //qDebug() << "free last"; 00065 delete [] data; 00066 delete copyCount; 00067 } else { 00068 --(*copyCount); 00069 //qDebug() << "free " << (*copyCount); 00070 } 00071 data = 0; 00072 size = 0; 00073 copyCount = 0; 00074 } 00075 } 00076 00077 template<class T> void SharedArray<T>::setSize(int newSize) 00078 { 00079 free(); 00080 if(newSize > 0) 00081 { 00082 data = new T[newSize]; 00083 size = newSize; 00084 copyCount = new int; 00085 *copyCount = 1; 00086 } 00087 } 00088 00089 template<class T> inline int SharedArray<T>::getSize() 00090 { 00091 return size; 00092 } 00093 00094 template<class T> T* SharedArray<T>::getData() 00095 { 00096 return data; 00097 } 00098 00099 template<class T> inline T& SharedArray<T>::operator[](int i) 00100 { 00101 return *(data + i); 00102 } 00103 00104 template<class T> inline const T& SharedArray<T>::operator[](int i) const 00105 { 00106 return *(data + i); 00107 } 00108 00109 template<class T> void SharedArray<T>::set(const SharedArray<T> &source) 00110 { 00111 //qDebug() << "SharedData set"; 00112 data = source.data; 00113 size = source.size; 00114 copyCount = source.copyCount; 00115 if(copyCount != 0) { 00116 ++(*copyCount); 00117 //qDebug() << "count " << (*copyCount); 00118 } else { 00119 //qDebug() << "count 0"; 00120 } 00121 } 00122 00123 #endif // SharedArray_H