This is a pointer class of mine that I would like to have reviewed. Right now it only allocates in the stack and has no copy or move operations.
template<typename T>
class Ptr {
public:
Ptr(T* t, int s = 1) :p{t},sz{s} { }
T& operator*() {
check_range();
return *p;
}
T& operator[](int i) {
check_range(i);
return p[i];
}
Ptr& operator+(int i) {
index += i;
check_range(index);
p+= i;
return *this;
}
Ptr& operator-(int i) {
index -= i;
check_range(index);
p -= i;
return *this;
}
Ptr& operator++() {
*this = *this+1;
return *this;
}
Ptr operator++(int) {
Ptr<T> old{p};
++(*this);
return old;
}
Ptr& operator--() {
*this = *this-1;
return *this;
}
Ptr operator--(int) {
Ptr<T> old{p};
--(*this);
return old;
}
private:
T* p;
int sz;
int index = 0;
void check_range(int i) {
if (i < 0 || i > sz-1) {
throw std::out_of_range("out of range");
}
}
void check_range() {
if (p == nullptr) {
throw std::out_of_range("null pointer");
}
}
};
How can I make this shorter and less ugly? Is there a better solution than what I did?