通过引用或值传递函数
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;
}
考虑到上面的代码,当我们尝试传递函子时,将myfn
或&myfn
传递给min_element
有什么区别吗?
通常,按引用传递和按值传递仅指传递变量,而不引用函数。(模板函数引入了一些复杂性,但这是另一个讨论。在这里,您将myfn
作为指向函数的指针传递。如果您改用&myfn
,则没有区别。编译器将隐式myfn
转换为指向具有该名称的函数的指针。
如果我们把myfn或&myfn传递给min_element有什么区别吗?
不。 无论如何,myfn
都会隐式转换为指向函数的指针。所以根本没有区别。
相关文章:
- 通过键入的引用问题传递函数
- 如何在构造函数中传递 const 引用时强制编译器不接受右值
- 按引用传递函数参数
- 如何在类的其他成员函数中重用传递的引用?
- 通过在引用线程对象来传递取消引用的“this”指针来在函数对象构造函数中创建线程是好是坏
- 将函数返回值传递给引用参数会导致 GCC 中的编译错误
- 在此函数中传递带有引用的参数
- 是否可以通过引用传递函数对象
- 通过引用或值传递函数
- 我应该通过值传递std::函数还是通过(rvvalue)-引用传递函数
- 通过引用传递函数,我在VS2012上运行它,为什么它会出错
- 如何通过引用c++来传递函数外的动态数组
- 按值或常量引用传递函数
- C++函数重载分辨率,涉及按值传递、引用和常量引用
- 通过引用传递函数指针
- 将智能指针传递给引用指针参数的函数
- 不能将lambda函数作为函数引用传递
- 通过值传递函数对象vs通过引用传递函数对象(c++)
- c++在同一个函数中返回字符串引用和传递字符串引用
- 将long类型的number传递给函数(引用vs值)(c++)