在《c++primer第五版》的p504中关于重载->的代码部分
class StrBlobPtr{
public:
std::string& operator* () const
{
auto p=check(curr,"dereference past end");
return (*p)[curr];
}
std::string* operator->()const
{
return & this->operator*();
}
private:
share_ptr<vector<string>>
check(size_t,const string&)const;
weak_ptr<vector<string>>wptr;
size_t curr;
}
在函数operator->中,语句return & this->operator*();
中调用->操作符,但是调用这个函数的对象不应该正是StrBlobPtr对象吗?那样this指针指向的是该类的对象,不会造成死循环吗?
return & this->operator*();中调用->操作符是通过指针调用,因此是原始的没有重载的含义,而operator->必须通过对象来调用!因此不会出现死循环。
StrBlobPtr a;
StrBlobPtr pa = &a;
a->empty(); //调用重载函数,因为a是对象
pa->curr; //出错,因为pa为指针,->为原始含义,因此引用了私有成员