Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it preferable to write func( const Class &value )?

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.

like image 768
casualcoder Avatar asked Nov 27 '22 22:11

casualcoder


1 Answers

There are 2 large semantic differences between the 2 signatures.

The first is the use of & in the type name. This signals the value is passed by reference. Removing this causes the object to be passed by value which will essentially pass a copy of the object into the function (via the copy constructor). For operations which simply need to read data (typical for a const &) doing a full copy of the object creates unnecssary overhead. For classes which are not small or are collections, this overhead is not trivial.

The second is the use of const. This prevents the function from accidentally modifying the contents of value via the value reference. It allows the caller some measure of assurance the value will not be mutated by the function. Yes passing a copy gives the caller a much deeper assurance of this in many cases.

like image 155
JaredPar Avatar answered Nov 29 '22 11:11

JaredPar