重载箭头运算符返回对象的地址而非对象?

C++语言 码拜 9年前 (2015-11-12) 1005次浏览
C++ Primer, Fifth Edition:这个类的最后一行,为何返回的是地址?本人一直觉得应该是返回对象return this->operator*(); 才对啊。不是说p->mem 和(*p).mem应该是一样的吗?

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*();    //就是这里
    }    
};
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 any work of its own by calling the dereference
 operator and returning the address of the element returned by that operator.
解决方案:8分
返回的的是地址,然后编译器来对该地址解引用获取对象,再取对象的成员~
解决方案:8分
operator-> 是有特殊规定的:
N4527 § 13.5.6
An expression x->m is interpreted as (x.operator->())->m for a class object x of type T if T::operator->() exists and if the operator is selected as the best match function by the overload resolution mechanism (13.3).
现在看来,把 x->m 解释成 (x.operator->()).m 而非 (x.operator->())->m 可能确实更好。不止本人一个人这么想:http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3723.html
解决方案:4分
operator->的作用,
就是把 A类型当作一个B类型指针用。
返回一个 B类型的指针。
然后 就可以把A类型的对象,当成B类型的指针
 使用指向运算符了->。
smartpointer 类型。
一般要实现两个运算符重载,
一个是  operator*
一个是 operator->
这样当成指针使用了 
operator* 返回B类型的引用。B&,const B&; 
operator->返回B类型的指针B*,const B*;

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明重载箭头运算符返回对象的地址而非对象?
喜欢 (0)
[1034331897@qq.com]
分享 (0)