Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use const references over const value in function?

On a 64-bit system, const& is 8 bytes. For values and objects smaller than 8 bytes, it makes sense to pass by value rather than reference. Even an 8 byte object is cheaper to copy than to pass the reference, then access the object.

At what threshold should you prefer a const reference over a const value?

like image 564
notwithoutend Avatar asked Mar 17 '14 15:03

notwithoutend


1 Answers

For values and objects smaller than 8 bytes, it makes sense to pass by value rather than reference. Even an 8 byte object is cheaper to copy than to pass the reference, then access the object.

References are not guaranteed to be implemented as pointers. In fact as per §8.3.2/4:

It is unspecified whether or not a reference requires storage


At what threshold should you prefer a const reference over a const value?

The situation is pretty simple:

  • use const references when you just want to read the value
  • use value when you will always end up making a copy of the object inside the function
  • use reference when you want to modify the object inside the function
like image 156
Shoe Avatar answered Nov 15 '22 07:11

Shoe