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

China☆狼群 提交于 2019-11-27 06:40:43

问题


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

ptr->a();

and

(*ptr).a(); 

?


回答1:


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




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/2470255/c-difference-between-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!