gpt4 book ai didi

c++ - 函数对象的好处?

转载 作者:太空狗 更新时间:2023-10-29 19:58:56 27 4
gpt4 key购买 nike

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

最佳答案

主要好处是对函数对象(仿函数)的调用通常是可内联的,而对函数指针的调用通常不是(主要示例是将 C 的 qsort 与 C++ 的 std::排序)。对于非平凡的对象/比较器,C++ 应该会扼杀 C 的排序性能。

还有其他好处,例如,您可以在仿函数中绑定(bind)或存储状态,而原始函数无法用它来实现。

编辑抱歉没有直接引用,但 Scott Meyers 声称在某些情况下提高了 670%: Performance of qsort vs std::sort?

编辑 2性能说明的段落是这样的:

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

关于c++ - 函数对象的好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16369807/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com