template class Array { public: Array(unsigned arraySize): data(0), size(arraySize), refCount(new long unsigned) { if(size > 0) data = new T[size]; *refCount = 1; } ~Array() { decRefCount(); } Array(const Array& cpy): data(cpy.data), size(cpy.size), refCount(cpy.refCount) { ++(*refCount); } const Array& operator=(const Array& cpy) { // Check for assignment onto itself: if(data == cpy.data) return *this; decRefCount(); data = cpy.data; size = cpy.size; refCount = cpy.refCount; ++(*refCount); return *this; } void setValue(unsigned index, const T& value) { copyOnWrite(); if(index < size) data[index] = value; } T getValue(unsigned index) const { if(index < size) return data[index]; else return T(); } private: T* data; unsigned size; unsigned long* refCount; void decRefCount() { --(*refCount); if(*refCount == 0) { if(data) { delete[] data; data = 0; } delete refCount; refCount = 0; } } void copyOnWrite() { if(*refCount > 1 && size > 0) { --(*refCount); refCount = new unsigned long; *refCount = 1; T* oldData = data; data = new T[size]; for(unsigned i = 0; i < size; ++i) data[i] = oldData[i]; } } };