I was given some code in which some of the parameters are pointers, and then the pointers are dereferenced to provide values. I was concerned that the pointer dereferencing wou
You should see the generated assembly code for the target machine... take into account that a function call is always done in constant time, and on actual machines that time is really negligible...
This will get voted down since it's Old Skool, but I often prefer pointers since it's easier to just glance at code and see if my objects that I am passing to a function could get modified, especially if they are simple datatypes like int and float.
All the other answers already point out that neither function is superior to the other in terms of runtime performance.
However, I think that that the former function is superior to the other in terms of readability, because a call like
f( &a, &b );
clearly expresses that a reference to some variable is passed (which, to me, rings the 'this object might be modified by the function' bell). The version which takes references instead of pointers just looks like
f( a, b );
It would be fairly surprising to me to see that a
changed after the call, because I cannot tell from the invocation that the variable is passed by reference.
Here's the difference in the generated assembly with g++. a.cpp
is pointers, b.cpp
is references.
$ g++ -S a.cpp
$ g++ -S b.cpp
$ diff a.S b.S
1c1
< .file "a.cpp"
---
> .file "b.cpp"
4,6c4,6
< .globl __Z7MyFunc1PiS_
< .def __Z7MyFunc1PiS_; .scl 2; .type 32; .endef
< __Z7MyFunc1PiS_:
---
> .globl __Z7MyFunc1RiS_
> .def __Z7MyFunc1RiS_; .scl 2; .type 32; .endef
> __Z7MyFunc1RiS_:
Just the function name is slightly different; the contents are identical. I had identical results when I used g++ -O3
.
My rule of thumb is to pass by pointer if the parameter can be NULL, ie optional in the cases above, and reference if the parameter should never be NULL.
References are very similar to pointers with one big difference: references can not be NULL. So you no not need to check if they are acutual usable objects (like for pointers).
Therefore I assume that compilers will produce the same code.