I think the following is really basic but I don’t really get what would be the “advantages” of one of these code.
Having this:
int main()
{
int a = 10;
f(a);
return 0;
}
What would be the difference between
void f(int& a)
{
int& b = a;
}
and
void f(int& a)
{
int b = a;
}
In particular, in the case where f would instead be the constructor of a class and where instead of an int we have a big object.
I would go with the second possibility… What do you think ?
Thanks.
Edit:
First, looking at the answers, I though I was brain dead when I posted the question, but actually I found interesting subquestions (and answers !) in the comments.
First:
The caller passes in an
a, which we get as a reference to the caller’sa. Then we create a new referecebwhich refers toa, which is still the caller’sa. As a result, any changes the caller makes will be visible tofand its containing class, and any changes made infto eitheraorbwill affect what the caller passed in asa.Here,
bis a new variable, anint, which takes a copy ofa. Changes made tobwon’t affect the caller, nor will the caller affectb. But a quicker way of writing the same thing is:and dispense with the
areference entirely. In particular, this shows in the prototype that the function will not modify its parameter, because it cannot; while a prototype ofvoid f (int &a)indicates that it may modifya.Edit: if you need to avoid any copying, a Third Option ™ is a reference to const:
inside
f, neitheranorbcan be modified, so it can’t affect the caller, but copying is avoided by using a reference to const. There is still a potential problem that any changes toacaused by the caller will be visible inside the object, because there is only one actual data itemaand many names for it; that’s something you’d have to document to ensure the caller does not do any such thing.