什么时候通过引用和地址传递函数参数?

时间:2022-05-20 16:02:14

Could anyone explain with some examples when it is better to call functions by reference and when it is better to call by address?

任何人都可以通过一些例子解释什么时候最好通过引用调用函数,什么时候最好通过地址调用?

3 个解决方案

#1


2  

Pass your arguments to function using reference whenever possible. Passing arguments by reference eliminate the chance of them being NULL. If you want it to be possible to pass NULL value to a function then use pointer.

尽可能使用引用将参数传递给函数。通过引用传递参数消除了它们为NULL的可能性。如果您希望可以将NULL值传递给函数,则使用指针。

#2


3  

This has already been discussed. See Pointer vs. Reference.

这已经讨论过了。请参阅指针与参考。

#3


2  

One nice convention is to:

一个很好的约定是:

  • Pass objects by pointer whenever they may be manipulated (side-effect or as output) by the function.
  • 只要可以通过函数操作(副作用或作为输出),就可以通过指针传递对象。

  • Pass all other objects by const reference.
  • 通过const引用传递所有其他对象。

This makes it very clear to the caller, with minimal documentation and zero performance cost, which parameters are const or not.

这使得调用者非常清楚,只需要很少的文档和零性能成本,哪些参数是常量。

You can apply this to primitive types as well, but it's debatable as to whether or not you need to use const references for non-output parameters, since they are clearly pass-by-value and cannot act as output of the function in any way (for direct types - not pointers/references - of course).

你也可以将它应用于原始类型,但是你是否需要对非输出参数使用const引用是有争议的,因为它们显然是按值传递的,不能以任何方式作为函数的输出(对于直接类型 - 当然不是指针/引用)。

#1


2  

Pass your arguments to function using reference whenever possible. Passing arguments by reference eliminate the chance of them being NULL. If you want it to be possible to pass NULL value to a function then use pointer.

尽可能使用引用将参数传递给函数。通过引用传递参数消除了它们为NULL的可能性。如果您希望可以将NULL值传递给函数,则使用指针。

#2


3  

This has already been discussed. See Pointer vs. Reference.

这已经讨论过了。请参阅指针与参考。

#3


2  

One nice convention is to:

一个很好的约定是:

  • Pass objects by pointer whenever they may be manipulated (side-effect or as output) by the function.
  • 只要可以通过函数操作(副作用或作为输出),就可以通过指针传递对象。

  • Pass all other objects by const reference.
  • 通过const引用传递所有其他对象。

This makes it very clear to the caller, with minimal documentation and zero performance cost, which parameters are const or not.

这使得调用者非常清楚,只需要很少的文档和零性能成本,哪些参数是常量。

You can apply this to primitive types as well, but it's debatable as to whether or not you need to use const references for non-output parameters, since they are clearly pass-by-value and cannot act as output of the function in any way (for direct types - not pointers/references - of course).

你也可以将它应用于原始类型,但是你是否需要对非输出参数使用const引用是有争议的,因为它们显然是按值传递的,不能以任何方式作为函数的输出(对于直接类型 - 当然不是指针/引用)。