How arrow-> operator overloading works internally in c++?

后端 未结 2 1392
别跟我提以往
别跟我提以往 2020-12-12 14:30

I understand the normal operator overloading. Compiler can translate them to method call directly. I am not very clear about the -> operator. I was writing my first custom i

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-12 15:12

    The operator-> has special semantics in the language in that, when overloaded, it reapplies itself to the result. While the rest of the operators are applied only once, operator-> will be applied by the compiler as many times as needed to get to a raw pointer and once more to access the memory referred by that pointer.

    struct A { void foo(); };
    struct B { A* operator->(); };
    struct C { B operator->(); };
    struct D { C operator->(); };
    int main() {
       D d;
       d->foo();
    }
    

    In the previous example, in the expression d->foo() the compiler will take the object d and apply operator-> to it, which yields an object of type C, it will then reapply the operator to get an instance of B, reapply and get to A*, after which it will dereference the object and get to the pointed data.

    d->foo();
    // expands to:
    // (*d.operator->().operator->().operator->()).foo();
    //   D            C            B           A*
    

提交回复
热议问题