简体   繁体   中英

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

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

ptr->a();

and

(*ptr).a(); 

?

[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.

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 "*.".

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM