To illustrate the increment and decrement operators, we’ll define these operators for our StrBlobPtr
class (§ 12.1.6, p. 474):
class StrBlobPtr {
public:
// increment and decrement
StrBlobPtr& operator++(); // prefix operators
StrBlobPtr& operator--();
// other members as before
};
To be consistent with the built-in operators, the prefix operators should return a reference to the incremented or decremented object.
The increment and decrement operators work similarly to each other—they call check
to verify that the StrBlobPtr
is still valid. If so, check
also verifies that its given index is valid. If check
doesn’t throw an exception, these operators return a reference to this object.
In the case of increment, we pass the current value of curr
to check
. So long as that value is less than the size of the underlying vector
, check
will return. If curr
is already at the end of the vector
, check
will throw:
// prefix: return a reference to the incremented/decremented object
StrBlobPtr& StrBlobPtr::operator++()
{
// if curr already points past the end of the container, can't increment it
check(curr, "increment past end of StrBlobPtr");
++curr; // advance the current state
return *this;
}
StrBlobPtr& StrBlobPtr::operator--()
{
// if curr is zero, decrementing it will yield an invalid subscript
--curr; // move the current state back one element
check(curr, "decrement past begin of StrBlobPtr");
return *this;
}
The decrement operator decrements curr
before calling check
. That way, if curr
(which is an unsigned
number) is already zero, the value that we pass to check
will be a large positive value representing an invalid subscript (§ 2.1.2, p. 36).