When to use const references over const value in f

2020-03-19 03:28发布

问题:

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?

回答1:

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