Posted: Sat Jun 16, 2007 5:50 pm
It is not too hard. Here is one that is smart to check it's bounds. I decided to try and see if I could make something even remotely useful.hmm...smart pointers just seem like too much overhead for such a commonly done thing(I tend to use too many pointers though)
Code: Select all
template <class T> class cPointer
{
private:
T *___ptr;
uintptr_t ___bytes;
uint32_t ___index;
public:
cPointer()
{
___ptr = 0;
___bytes = 0;
___index = 0;
}
~cPointer()
{
if(___ptr)
{
delete [] ___ptr;
}
___ptr = 0;
___bytes = 0;
___index = 0;
}
uint32_t New(uint32_t itemCount)
{
if(___ptr)
{
delete [] ___ptr;
}
if(itemCount < 1)
{
___ptr = 0;
return 0;
}
___ptr = (T*)new T[itemCount];
___bytes = sizeof(T) * itemCount;
___index = 0;
return ___bytes;
}
cPointer& operator=(cPointer &a)
{
___ptr = a.___ptr;
return *this;
}
cPointer& operator=(T *a)
{
___ptr = a;
return *this;
}
T& operator[](int index)
{
if((index * sizeof(T)) >= ___bytes)
{
throw("Access out of bounds for pointer to array.\n");
}
return ___ptr[index];
}
void operator++()
{
++___index;
}
void operator--()
{
--___index;
}
T& operator*()
{
if((___index * sizeof(T)) >= ___bytes)
{
throw("Access out of bounds for pointer to array.\n");
}
return ___ptr[___index];
}
};
int main(int argc, char *argv[])
{
cPointer<uint32_t> ptr;
ptr.New(5);
*ptr = 12;
++ptr;
--ptr;
uint32_t x = *ptr;
printf("%u\n", x);
return 1;
}
The majority of kernel and driver functions are going to deal with pages or regions of memory, but only occasionally (I figure) you would deal with a small array that was dynamically created, or passed to a driver through some mechanism. You might even create a static array at compile time and include bounds checking by using one similar to:
Code: Select all
template <class T, int C> cPointer{
private:
T ___const[C];
....
};