//Smart array pointer. The last array element must be zero, or
//it must evaluate to zero when cast to bool.
template<class T, class CopyType>
class SmartArrayPtr
{
//Control variable to avoid copies to involuntarily release
//the array.
bool _isCopy;
void ReleaseArray(void)
{
if (ptr && !_isCopy)
{
//int i = 0;
//while (ptr[i])
//{
// CopyType::destroy(&ptr[i]);
// i++;
//}
delete[] ptr;
ptr = NULL;
}
}
public:
T *ptr;
SmartArrayPtr<T, CopyType>() : ptr(NULL), _isCopy(false)
{ }
//Initialization constructors
SmartArrayPtr<T, CopyType>(T *thePtr) : ptr(thePtr), _isCopy(false)
{ }
//Copy constructor
SmartArrayPtr<T, CopyType>(const SmartArrayPtr<T, CopyType>& src) : ptr(src.ptr), _isCopy(true)
{ }
~SmartArrayPtr()
{
ReleaseArray();
}
T* Detach()
{
T *oldPtr = ptr;
ptr = NULL;
return oldPtr;
}
T& operator[](int index)
{
return ptr[index];
}
T& operator=(T *newPtr)
{
ReleaseArray();
ptr = newPtr;
return ptr;
}
T& operator&()
{
return &ptr;
}
};
Whenever the object is destroyed, the ReleaseArray() routine jumps in and deletes the array. But what if T = const SomeDataType? How can I re-write ReleaseArray() so it accounts for constness?
I hope it is clear, but let me know if not. Thanks!
First of all, I see that you added the const keyword twice in certain overloads. Why is that? Shouldn't just one of those suffice?
Second: I have read a bit about the mutable keyword. In short, it seems that mutable allows the contents of a variable to change from const members. I don't think I want that. I want a way to avoid the call to delete[] in ReleaseArray(). The array received is const because it is allocated in the stack. Example:
There's no way to distinguish dynamic from non-dynamic arrays with just a pointer. The user will have to somehow tell the class how the array was created.