Newbie here, I am reading some code, and I see sometimes the author used the reference in a function as
funca (scalar& a)
// Etc
Sometimes he just use
funcb (scalar a)
// Etc
What’s the difference? Is using a reference a good habit that I should have?
Thank you!
If you call
foo(scalar a), the argumentaof typescalarwill be COPIED from the caller and foo will have it’s own COPY of the original object.If you call
foo(scalar &b), the argumentbwill be just a reference to the original object, so you will be able to modify it.It’s faster to pass an object by reference using the &name syntax, since it avoids creating a copy of the given object, but it can be potentially dangerous and sometimes the behavior is unwanted because you simply want an actual copy.
That being said, there’s actually an option that disallows the ability to modify the original object for the called function yet avoids creating a copy. It’s
foo(const scalar &x)which explicitly states that the caller does not want the functionfooto modify the object passed as an argument.Optional reading, carefully:
There’s also a way of passing an argument as a raw pointer which is very rare in modern C++. Use with caution:
foo(scalar *a). The caller has got to provide the address of an object instead of the object itself in this scenario, so the caller would callfoo(&a). For the called functionfooto be able to modify the object itself in this case, it would need to dereference the pointera, like this infoo:*a =. The star in front of the variable name in this case says that we don’t want to modify the address that we have received (as a direct result of the calling function providing&a, that is, the address of the object a).