M
Me
Martin said:And that should be the same as:
void order(char*& pp1, char*& pp2)
This is exactly what is difficult for me to understand... hmmm. I guess
I'll have to spend some time looking at this...
It's simple, just keep in mind that in C++, *every* type is passed by
value (except for arrays but I'd consider that more like automatic
decomposition into pointers):
void foo(int a)
{
++a;
}
int j = 0;
foo(j);
foo(10); // works
after the call to foo, j is still 0.
void foo(int *a)
{
++*a;
}
int j = 0;
foo(&j);
foo(&10); // error
after the call to foo, j is 1.
void foo(int &a)
{
++a;
}
int j = 0;
foo(j);
foo(10); // error
after the call to foo, j is 1.
For the most part, T &var is exactly the same thing as T * const var
(which is one reason why it has to be initialized and can't be
reassigned later) except having a reference type buys you more things
over just having a pointer. One of the major ones is that the null
reference, *(T*)0, is undefined and with all this combined, this is how
C++ gets away with treating the reference as an automatically
dereferenced pointer.
What's really going to bake your noodle is this:
void foo(const int *a)
{
cout << *a;
}
int j = 0;
foo(&a);
foo(&10); // error
void foo(const int &a)
{
cout << a;
}
int j = 0;
foo(j);
foo(10); // ok
What happens here is that the compiler creates a temporary:
const int dummy = 10;
foo(dummy);
It used to work for regular references but it lead to very hard to
detect bugs like this one:
void foo(int &a)
{
++a;
}
float f = 0;
foo(f); // ok in ancient C++
because the compiler would turn this into:
float f = 0;
int dummy = f;
foo(dummy);
// whoops, the temporary gets incremented but not f