I typed the following example:
#include <iostream>
double f(double* x, double* y)
{
std::cout << "val x: " << *x << "\n";
std::cout << "val y: " << *y << "\n";
return *x * *y;
}
double f2(double &x, double &y)
{
std::cout << "val x: " << x << "\n";
std::cout << "val y: " << y << "\n";
return x * y;
}
int main()
{
double a, b;
a = 2;
b = 3;
std::cout << f(&a, &b) << "\n";
std::cout << f2(a, b) << "\n";
return 0;
}
In the function f
I declare x and y as pointers of which I can get the value by using *x
. When calling f
I need to pass the address of my passed arguments, that is why I pass &a, &b
. f2
is the same except the definition is different.
Now my question is: Are they both really the same concerning memory management? Both not making any copy of the passed value but instead passing a reference?
I wonder about f2
because I couldn't read out the address of x
in f2
so I know more about x and y in f
(there I know address AND value).
Edit: After doing some more research, I found a quite useful topic:
Pointer vs. Reference
There's also a link to google coding guidelines http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Reference_Arguments which is quite useful
I feel (as I understood now, it's a form of subject taste) to make more clear