std :: function function vs function pointer

时间:2017-10-26 03:39:47

标签: c++ c++11

fn1和fn2之间有什么区别,哪一个更好?

int half(int x) {return x/2;}

std::function<int(int)> fn1 = half;                    // function
std::function<int(int)> fn2 = &half;                   // function pointer


std::cout << "fn1(60): " << fn1(60) << '\n';
std::cout << "fn2(60): " << fn2(60) << '\n';

1 个答案:

答案 0 :(得分:4)

不,没有。

在第一个构造中,函数作为std::function传递给int (&) (int)构造函数 - 对函数的引用。

在第二个构造中,函数作为std::function传递给int (*) (int)构造函数 - 指向函数的指针。

callable本身存储在std::function对象中的方式是实现定义的。

构建完成后,fn1fn2的行为完全相同,并且没有区别。

至于#34;哪一个更好&#34; - 我更喜欢参考版本,因为句子对操作符的负担较少,而且无论如何,我的理念是尽可能少地使用指针,即使它是最安全的指针。

相关问题