If I have a function with all const references as arguments and another function with values...so in both the cases value will not get modified..so why is it preferred to use const reference?
Asked
Active
Viewed 116 times
0
-
1Reference points to the same object, pass by value copys the whole object. It is a matter of performance – RoQuOTriX Feb 18 '20 at 15:36
-
1@RoQuOTriX And semantics. Aside from possibility, as some cannot be copied. – Deduplicator Feb 18 '20 at 15:37
-
Basically, passing by value copies the object. Sometimes you can't copy an object and some times copying an object is expensive (like a container). Sometimes copying is better when the object is very small, like an `int` or a pointer. – François Andrieux Feb 18 '20 at 15:38
-
It's much more than performance. It's fundamentally a different thing to do (think about the effect of mutations) – Asteroids With Wings Feb 18 '20 at 15:46
1 Answers
1
Passing by value, basicaly creates a local copy of the argument, so passing by reference is better, but you might want to avoid the function to alter the variable you pass by reference, let's say you just want to print it on the screen, then you mark it as const
so it cannot be changed, and you avoid copying it making your program a bit more efficient. There can be other reasons to pass by reference, like, for instance, if some object cannot be copied.

anastaciu
- 23,467
- 7
- 28
- 53
-
3Why is this downvoted? It's correct. Lots of weird downvoting going on lately. – Asteroids With Wings Feb 18 '20 at 15:47