14.7. Member Access Operators
The dereference (*
) and arrow (->
) operators are often used in classes that represent iterators and in smart pointer classes (§ 12.1, p. 450). We can logically add these operators to our StrBlobPtr
class as well:
class StrBlobPtr {public: std::string& operator*() const { auto p = check(curr, "dereference past end"); return (*p)[curr]; // (*p) is the vector to which this object points } std::string* operator->() const { // delegate the real work to the dereference operator return & this->operator*(); } // other members as before};
The dereference operator checks that curr
is still in range and, if so, returns a reference to the element denoted by curr
. The arrow operator avoids doing ...
Get C++ Primer, Fifth Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.