何时在函数中的const值上使用const引用? [英] When to use const references over const value in function?
问题描述
在64位系统上, const&
是8个字节。对于小于8个字节的值和对象,按值而不是引用进行传递是有意义的。甚至复制一个8字节的对象也比传递引用然后访问该对象便宜。
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.
与const值相比,在什么阈值上您更喜欢const引用? / p>
At what threshold should you prefer a const reference over a const value?
推荐答案
对于小于8个字节的值和对象,按值传递而不是引用是有意义的。甚至8字节的对象也比传递引用然后访问该对象便宜。
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.
不能保证会实现引用作为指针。实际上,按照§8.3.2/ 4:
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
在const值而不是const值上,您希望在什么阈值上使用? p>
At what threshold should you prefer a const reference over a const value?
情况非常简单:
- 使用 const引用当您只想读取值时
- 使用 value 当您总是最终在其中复制对象时函数
- 要修改函数内部的对象,请使用引用
- 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
这篇关于何时在函数中的const值上使用const引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!