简体   繁体   English

通过引用或值传递函数?

[英]Passing function by reference or by value?

#include <iostream>
#include <algorithm>
using namespace std;

bool myfn(int i, int j) { return i<j; }



int main () {
int myints[] = {3,7,2,5,6,4,9};

 // using function myfn as comp:
cout << "The smallest element is " << *min_element(myints,myints+7,myfn) << endl;
cout << "The largest element is " << *max_element(myints,myints+7,myfn) << endl;

return 0;
}

considering the above code , is there any difference if we pass myfn or &myfn to min_element ? 考虑到上面的代码,如果我们将myfn&myfnmin_element有什么区别吗? when we tried to pass a functor which one would be a more standard way? 当我们试图传递一个更为标准的仿函数?

Typically, pass-by-reference and pass-by-value only refer to passing variables, not functions. 通常,pass-by-reference和pass-by-value仅指传递变量,而不是函数。 (Template functions introduce some complications, but that is for another discussion.) Here you are passing myfn as a pointer to a function. (模板函数引入了一些复杂性,但这是另一个讨论。)在这里,您将myfn作为指向函数的指针传递。 There is no difference if you use &myfn instead. 如果您使用&myfn则没有区别。 The compiler will implicitly convert myfn to a pointer to the function with that name. 编译器将隐式地将myfn转换为指向具有该名称的函数的指针。

is there any difference if we pass myfn or &myfn to min_element? 如果我们将myfn或&myfn传递给min_element有什么区别吗?

No. myfn gets implicitly converted into pointer-to-function , anyway. 不,无论如何, myfn被隐式转换为指向函数的指针 So there is no difference at all. 所以没有任何区别。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM