Why would one use func( const Class &value )
rather than just func( Class value )
? Surely modern compilers will do the most efficient thing using either syntax. Is this still necessary or just a hold over from the days of non-optimizing compilers?
Just to add, gcc will produce similar assembler code output for either syntax. Perhaps other compilers do not?
Apparently, this is just not the case. I had the impression from some code long ago that gcc did this, but experimentation proves this wrong. Credit is due to to Michael Burr, whose answer to a similar question would be nominated if given here.
The first example is pass by reference. Rather than pass the type, C++ will pass a reference to the object (generally, references are implemented with pointers... So it's likely an object of size 4 bytes)... In the second example, the object is passed by value... if it is a big, complex object then likely it's a fairly heavyweight operation as it involves copy construction of a new "Class".
Here are the differences between some parameter declarations:
where:
So the differences between
func(Class value)
andfunc(const Class &value)
are:value
value
If you use the former, and then try to change
value
, by accident, the compiler will give you an error.If you use the latter, and then try to change
value
, it won't.Thus the former makes it easier to catch mistakes.