问题
Is there a general difference between doing
(*ptr).method()
vs
ptr->method()
I saw this question in a comment on another question and thought I would ask it here. Although I just remembered that pretty much every operator in C++ can be overloaded, so I guess the answer will depend. But in general, is there a difference between doing one versus the other?
回答1:
As "jamesdlin" already noted, the *
and ->
operators can be overloaded for class types.
And then the two expressions (*ptr).method()
and ptr->method()
can have different effect.
However, for the built-in operators the two expressions are equivalent.
The ->
operator is more convenient when you're following a chain of pointers, because .
has higher precedence than *
, thus requiring a lot of ungrokkable parentheses.
Consider:
pBook->author->snailMail->zip
versus
(*(*(*pBook).author).snailMail).zip
回答2:
For raw pointer types, they are the equivalent.
And yes, for general types, the answer is indeed "it depends", as classes might overload operator*
and operator->
to have different behaviors.
回答3:
Yes. ptr->method()
is two characters shorter than (*ptr).method()
.
It is also prettier.
回答4:
C++ Standard 5.2.5/3:
If E1 has the type “pointer to class X,” then the expression E1->E2 is converted to the equivalent form (*(E1)).E2;
For non-pointer values operators could be overloaded.
回答5:
But in general, is there a difference between doing one versus the other?
No! (unless ->
and *
are explicitly overloaded to perform different functions)
ptr->method()
and (*ptr).method()
are equivalent.
回答6:
Sorry to dig this post, but even though the expressions in the OP are equivalent for raw pointer types, I think there is at least one important difference to be mentioned in C++, in addition to everything that has been said:
From Wikipedia (http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#cite_note-arrowptr-6):
The return type of operator->() must be a type for which the -> operation can be applied, such as a pointer type. If x is of type C where C overloads operator->(), x->y gets expanded to x.operator->()->y.
This implies that ->
is expected to return a dereferenceable type, whereas *
is expected to return a dereferenced type, and therefore this "chaining" applies to ->
only.
回答7:
The ->
sequence serves as a visual indicator that it is pointing to something. Both operators do the exact same sequence of operations.
回答8:
They are synonyms. The latter is a shorthand for the former.
来源:https://stackoverflow.com/questions/4263796/pointer-dereference-operator-vs