C++ - Difference between (*). and ->?

后端 未结 3 1656
猫巷女王i
猫巷女王i 2020-12-11 01:45

Is there any difference in performance - or otherwise - between:

ptr->a();

and

(*ptr).a(); 

?

相关标签:
3条回答
  • 2020-12-11 02:21

    The -> operator is special in that in most cases it "drills-down" recursively until the result of the expression is no longer something that has an overloaded -> operator defined for it. The (*subxpression).x expression only does one dereference on subexpression, so if the result of (*subexpression) is another pointer, then this wouldn't compile (you would need to write (*(*subexpression)).x. See the following code for a better illustration:

    #include <iostream>
    using namespace std;
    
    class MyClass
    {
    public:
        MyClass() : x(0) {}
        int x;
    };
    
    class MyPtr
    {
    private:
        MyClass* mObj;
    public:
        MyPtr(MyClass* obj) : mObj(obj) {}
        MyClass* operator->() 
        {
            return mObj;
        }
    };
    
    int main() 
    {
        MyClass obj;
        MyClass* objCPtr = &obj;
        MyClass** objCHandle = &objCPtr;
        MyPtr ptr(&obj);
        cout << ptr->x << endl;
        cout << (*(*objCHandle)).x << endl;
    }
    

    Note however, that this would not compile:

    cout << objCHandle->x << endl;
    

    Because the drill down behavior of -> only occurs when the left hand side of the expression is a class, struct, union, or generic type. In this case, objCHandle is a MyClass**, so it doesn't qualify.

    0 讨论(0)
  • 2020-12-11 02:24

    Since you are asking for it in the comments. What you are probably looking for can be found in the Standard (5.2.5 Class member access):

    3 If E1 has the type “pointer to class X,” then the expression E1->E2 is converted to the equivalent form (*(E1)).E2;

    The compiler will produce the exact same instructions and it will be just as efficient. Your machine will not know if you wrote "->" or "*.".

    0 讨论(0)
  • 2020-12-11 02:35

    [Edit]

    If the variable is defined as T* (where T is some type) then both -> and * are the same (unless ptr is null).

    If the variable is an instance of a class (by value or by reference) then -> and * should behave the same (per best practice) but this requires the class to overload them the same way.

    0 讨论(0)
提交回复
热议问题