通过值或通过引用传递基本数据类型更好吗? [英] Is it better to pass by value or by reference for basic datatypes?
问题描述
可能的重复项:
如何将对象传递给C ++中的函数?
在C ++中,是否有任何特定的情况比按常量引用"优先通过按值传递"?
我有一个这样实现的类的成员:
I have members of a class implemented like this:
void aaa(int a, float b, short c)
{
bbb(a, b);
}
void bbb(int a, float b)
{}
如果a,b和c的值作为常量存储在我的类中,那么使用下面或上面所示的函数会更好/更明智吗?
If the values of a, b and c were stored in my class as constants, then would it have been better/sensible to use my functions as shown below or as shown above?
void aaa(int& a, float& b, short& c)
void bbb(int& a, float& b)
在这种情况下,使用引用是否会带来任何速度上的好处或优势?任何不利之处/参考的开销?
Does using references give any speed benefits or advantages in this case? Any disadvantages/overheads of references here?
推荐答案
标准对实现引用没有任何限制,但是通常将它们实现为自动取消引用的指针(实际上有一些例外).您可能知道,在32位系统指针的大小为4个字节时,这意味着通过引用传递字符,短裤(sizeof()小于4个字节的类型)可能会被认为是过分杀人-使用4个字节而不是1个(字符)或2(短).通常,这取决于是否使用约束或堆栈来传递参数:按值传递基本类型时,您可以节省一点堆栈,但是对于寄存器(即使是char),也将使用4个字节,因此没有意义尝试使用ptrs/refs优化某些内容.
Standard doesn't have constraints about implementation of references, however usually they're implemented as autodereferenced pointers (actually with some exceptions). As you probably know, on 32 bit system pointer size is 4 bytes, that means that passing chars, shorts (types with sizeof() less than 4 bytes) by reference maybe considered as somewhat overkilling - using 4 bytes instead of 1 (char) or 2 (short). In general it depends on whether the rigisters or stack is used for passing parameters: you can save a bit of stack when passing basic types by value, but in case of registers even for chars, 4 bytes will be used, so there's no point in trying to optimize something with ptrs/refs.
这篇关于通过值或通过引用传递基本数据类型更好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!