Question about references
I think the following is really basic but I don't really get what would be the "advantages" of one of these code.
Hav开发者_运维知识库ing 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:
void f(int& a) {
int& b = a;
}
The caller passes in an a
, which we get as a reference to the caller's a
. Then we create a new referece b
which refers to a
, which is still the caller's a
. As a result, any changes the caller makes will be visible to f
and its containing class, and any changes made in f
to either a
or b
will affect what the caller passed in as a
.
void f(int& a) {
int b = a;
}
Here, b
is a new variable, an int
, which takes a copy of a
. Changes made to b
won't affect the caller, nor will the caller affect b
. But a quicker way of writing the same thing is:
void f(int b) {
}
and dispense with the a
reference entirely. In particular, this shows in the prototype that the function will not modify its parameter, because it cannot; while a prototype of void f (int &a)
indicates that it may modify a
.
Edit: if you need to avoid any copying, a Third Option (tm) is a reference to const:
void f(const int &a) {
const int &b = a;
}
inside f
, neither a
nor b
can 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 to a
caused by the caller will be visible inside the object, because there is only one actual data item a
and many names for it; that's something you'd have to document to ensure the caller does not do any such thing.
int& b = a
does not copy a, int b = a
does.
Most importantly, the caller of your constructor can change the object and you will see those changes in your new object. Even worse: If the caller destroys the object (or it is automatically destroyed), your object has an invalid reference.
The second version creates a copy of the variable while the first one only generates another reference to the original object. If you just have a reference, Bad Things (tm) will happen if the caller destroys his object. So you most likely want to go with the second version (unless you can be sure using a reference is safe).
精彩评论