I was told to change all pass by value or pass by reference arguments in a Qt/C++ application to pass by const reference. All Qt types (QString for instance) are concerned, but not native types (double, integer). Could you explain more precisely why, or point to reference?
-
http://stackoverflow.com/questions/2582797/why-pass-by-const-reference-instead-of-by-value – acraig5075 Jul 10 '12 at 07:47
-
[Pass by Reference/Value in C++](http://stackoverflow.com/questions/410593/pass-by-reference-value-in-c), [What's the difference between passing by reference vs. passing by value?](http://stackoverflow.com/questions/373419/whats-the-difference-between-passing-by-reference-vs-passing-by-value#373429), [Is it better in C++ to pass by value or pass by constant reference?](http://stackoverflow.com/questions/270408/is-it-better-in-c-to-pass-by-value-or-pass-by-constant-reference) – Jesse Good Jul 10 '12 at 07:47
-
[Where should I prefer pass-by-reference or pass-by-value?](http://stackoverflow.com/questions/4986341/where-should-i-prefer-pass-by-reference-or-pass-by-value). – Jesse Good Jul 10 '12 at 07:47
-
Possible duplicate of [Where should I prefer pass-by-reference or pass-by-value?](https://stackoverflow.com/questions/4986341/where-should-i-prefer-pass-by-reference-or-pass-by-value) – ymoreau Apr 03 '18 at 12:44
2 Answers
Pass by value makes a local copy of the argument, so if a big structure is passed there might be quite a big loss of time and space. That's why big structures shall be passed by reference. But if the function/method really needs the copy of the parameter, then pass it by value.
On the other hand passing by reference makes the object vulnerable to changes - if the state of the object is changed in the function, the original object is modified since they are the same. That's why const reference is used: it prevents from changing/editing the object by mistake.
Another reason is polymorphism. When passing by value virtuality is lost, while passing by reference or pointer virtual methods work as expected.

- 6,391
- 4
- 36
- 44
When passing by reference we are passing the address of the same instance where pass by value involves copying of the object to another (via a copy constructor in case of QString
) native types like int, double etc will be smaller in size so there is less overhead comparing QString
like objects. By passing a const
reference we ensure that the object will not get modified in the passed function as the changes made by the called function affects the object passed as both points to the same location.

- 1,521
- 1
- 14
- 32