William said:
Hi,
References introduced make things much more complicated. e.g.
int a;
void f(int &n);
void g(int *p);
Isn't g(&a) much more clear than f(a), when we would change the value of
the lvalue a ?
Clearity is in the eye of the beholder
Seriously. It depends. In your above example it definitly is
not clear to the caller if
f(a)
will change 'a' or not.
But in practice this is much less an issue then you think. Mostly
because in real life functions are not called 'f' and arguments are
not called 'a'. In
j = CalcFibonacci( InputNumber );
will the function CalcFibonacci alter the passed argument? While
there is no 100% guarantee, bets are good, that it won't.
Same for eg. the prototype
void Deposit( Account& TheAccount, long Amount );
Now guess: Will The Account be changed when the function is called.
If you read the callers code:
Account CustomerAccount;
long Amount;
CustomerAccount = AskForCustomer();
Amount = AskForAmount();
Deposit( CustomerAccount, Amount );
When you read that code, and have no idea that the first argument
to Deposit is passed by reference, would you expect CustomerAccount
to change? Sure I would! If I deposit something on an account, then
the amount associated with that account changes.
Are there any efficiency differences ?
When you pass a pointer, it is the functions responsibility to at
least check that the passed pointer is not 0. On the other hand,
if you pass per reference AND the function gets inlined, you open
a lot of possibilities for the compiler for optimizations.
Is reference a must in c++ ?
Yes. Otherwise writing custom operators would not be possible.
Granted, we could live without that feature (although it is a
nice one) and then AFAIK there would be no killer argument for
not dropping references.