operator->智能指针的返回值

ric*_*d.g 5 c++ pointers

像shared_ptr这样的智能指针可以像普通指针一样使用*->运算符.书中说->运算符返回shared_ptr存储的指针.因此,您可以使用它来访问此指针指向的对象.但我在这里很困惑.看下面的代码.

class A
{
public:
    A(int v = 20){val = v;}
    int val;
}
A* p1 = new A;
std::cout<<p1->val;  //This is common sense

boost::shared_ptr<A> p2(new A);
std::cout<<p2->val;  //This is right
//My question is that p2-> returns the pointers of the object, then maybe another 
//-> should be used?
//like (p2->)->val? 
Run Code Online (Sandbox Code Playgroud)

jro*_*rok 10

这是魔法.好吧,更像是一个特例.标准说

13.5.6类成员访问[over.ref]

1 operator->应该是不带参数的非静态成员函数.它实现了使用的类成员访问语法->.

post fi x-expression - > templateopt id-expression
post fi x-expression - > pseudo-destructor-name

表达式x->m被解释为(x.operator->())->mx类型为Tif 的类对象,如果T::operator->() 操作符被重载决策机制选为最佳匹配函数(13.3).

也就是说,operator->再次调用重载运算符的结果.如果那个也被重载,它会递归地继续,直到原始指针是结果并且内置operator->被调用.

这并不意味着结果不能是任意类型 - 它可以,但是你只能用函数调用语法调用它:

struct X {
    int operator->() { return 42; }
};

int main()
{
    X x;
    x.operator->(); // this is OK
}
Run Code Online (Sandbox Code Playgroud)