When to use const references over const value in function?

后端 未结 1 734
南笙
南笙 2021-01-12 15:36

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 ob

相关标签:
1条回答
  • 2021-01-12 15:55

    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
    0 讨论(0)
提交回复
热议问题