函数对象的好处? [英] The benefit of function objects?

查看:715
本文介绍了函数对象的好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在STL中使用的函数对象只是简单的对象,我们可以像函数一样操作它。我可以说函数和函数对象的工作是一样的。如果它是真的,那为什么我们应该使用函数对象而不是函数?

I have known that the function objects used in STL is just simple object that we can operator it like a function. That I can say the works of function and function objects is the same. If it's true, then why we should used function object rather than function?

推荐答案

主要的好处是对函数对象(functor)的调用通常是可内联的,其中对函数指针的调用通常不是(例如,比较C的 qsort 和C ++的 std :: sort )。对于非平凡的对象/比较器,C ++应该杀死C的排序性能。

The primary benefit is that calls to function objects (functors) are generally inlineable, where as calls to function pointers are generally not (prime example is comparing C's qsort to C++'s std::sort). For non-trivial objects/comparators, C++ should kill C's performance for sorting.

还有其他好处,例如你可以绑定或存储状态在函子中,这是一个原始的功能,你不能做。

There are other benefits, for example you could possibly bind or store state in a functor, with which a raw function you cannot do.

编辑
抱歉没有直接参考,但Scott Meyers声称在某些情况下有670%的改进:
qsort vs std :: sort的性能?

编辑2
效果说明的段落是:

Edit 2 The passage with the performance note is this:


函数指针参数禁止内联解释了一个长期的C程序员经常发现很难相信的
观察:
C ++的排序几乎总是尴尬C的qsort当它涉及到
速度。当然,C ++有函数和类模板实例化和
有趣的操作符()函数调用,而C做一个简单的
函数调用,但所有的C ++开销被吸收
汇编。在运行时,排序使得内联调用它的比较
函数(假设比较函数已经声明为inline
并且其主体在编译期间可用),而qsort通过指针调用其
比较函数。最终结果是sort
运行得更快。在我测试一个一百万双打的矢量,它跑了
快了670%,但不要采取我的话,它自己试试。它是
容易验证当比较函数对象和真实函数
作为算法参数时,有一个抽象奖金。

The fact that function pointer parameters inhibit inlining explains an observation that long-time C programmers often find hard to believe: C++’s sort virtually always embarrasses C’s qsort when it comes to speed. Sure, C++ has function and class templates to instantiate and funny-looking operator() functions to invoke while C makes a simple function call, but all that C++ "overhead" is absorbed during compilation. At runtime, sort makes inline calls to its comparison function (assuming the comparison function has been declared inline and its body is available during compilation) while qsort calls its comparison function through a pointer. The end result is that sort runs faster. In my tests on a vector of a million doubles, it ran up to 670% faster, but don’t take my word for it, try it yourself. It’s easy to verify that when comparing function objects and real functions as algorithm parameters, there’s an abstraction bonus.



-Scott Meyers "Effective STL: 50 Specific Ways to Improve Your Use of the Standard Template Library" - Item 46

这篇关于函数对象的好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆