Is there any difference in performance - or otherwise - between:
ptr->a();
and
(*ptr).a();
?
The & is a unary operator in C which returns the memory address of the passed operand. This is also known as address of operator. <> The * is a unary operator which returns the value of object pointed by a pointer variable. It is known as value of operator.
* can be either the dereference operator or part of the pointer declaration syntax. & can be either the address-of operator or (in C++) part of the reference declaration syntax.
The dot ( . ) operator is used to access a member of a struct, while the arrow operator ( -> ) in C is used to access a member of a struct which is referenced by the pointer in question.
Difference between Dot(.)The Dot(.) operator is used to normally access members of a structure or union. The Arrow(->) operator exists to access the members of the structure or the unions using pointers.
[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 "*.".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With