What does a function prototype mean with an ampersand in it? [duplicate]

断了今生、忘了曾经 提交于 2019-11-28 05:17:27

问题


Possible Duplicate:
What does the '&' operator do in C++?

In my CS class today the teacher showed us some examples of functions and templates and some of the prototypes for functions had ampersands in the list of parameters like this:

void exchange( T & x, T & y ) ; // prototype

what does that mean? What should I use it for?


回答1:


the & is for reference. In short that's something like a pointer, that can't be NULL. Wikipedia has something on this topic here.

References are cheap when they are used in function/method calls, since the object doesn't need to be copied in your function call. You still have the same syntax as if you had with a copied object. With pointers you would need to handle the special case, that the pointer is NULL.

That is a usual reason to use them. If I guess right and exchange means something like swap the tow objects x and y, the the cost of the function call is directly related to the cost of coping the object, so saving some copies may be a relevant optimization.




回答2:


The & means 'reference to' - x is a reference to a T, not a copy.



来源:https://stackoverflow.com/questions/9488894/what-does-a-function-prototype-mean-with-an-ampersand-in-it

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