Is it better to pass by value or by reference for basic datatypes? [duplicate]

怎甘沉沦 提交于 2019-12-30 08:11:46

问题


Possible Duplicates:
How to pass objects to functions in C++?
is there any specific case where pass-by-value is preferred over pass-by-const-reference in 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)
{}

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?


回答1:


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.




回答2:


In the case of ordinal types — i.e. int, float, bool, etc. — there is no savings in using a reference instead of simply using pass by value. Source Source2




回答3:


If you use references, make them const:

void bbb(const int & a, const float & b);

Otherwise the semantics will be different from passing by value, as the function could change the value of the variables passed to the parameters. This would imply that you could not use literals for the arguments.




回答4:


I don't see the reason why it would be faster. You need to send the parameter to the function in both case. If the function get pointer instead of value, then the pointer needs dereferencing which might be slower than sending plain value.



来源:https://stackoverflow.com/questions/4112914/is-it-better-to-pass-by-value-or-by-reference-for-basic-datatypes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!