代码之家  ›  专栏  ›  技术社区  ›  Gab Royer

使用STL算法,传递函数指针还是函子更好?

  •  10
  • Gab Royer  · 技术社区  · 15 年前

    void fun(int i) {
      //do stuff
    }
    
    ...
    for_each(a.begin(), a.end(), fun);
    

    方法2:

    class functor {
    public:
      void operator()(int i);
    };
    
    ...
    for_each(a.begin(), a.end(), functor());
    

    编辑:应该这样表述,在什么情况下,上述方法中的一种比另一种更可取?

    6 回复  |  直到 15 年前
        1
  •  20
  •   Konrad Rudolph    15 年前

    函子可以(和)

    因此,函子有一个真正的性能优势,这在紧循环中可能是巨大的。此外,函子通常更容易组合,尤其是在STL中发挥更好的作用: std::bind x 例如,在函数指针上不起作用。

    我讨厌它们把代码弄得乱七八糟,但考虑到所有的优点,我更喜欢它们而不是函数指针。

        2
  •  11
  •   MSN    15 年前

    然而,在实践中,主要是为编译器提供足够的信息来进行有效的优化。

    例如Visual C++ 2008,给出了以下代码:

    #include "stdafx.h"
    #include <algorithm>
    
    const char print_me[]= "hello!";
    
    class print_functor
    {
    public:
        void operator()(char c)
        {
            printf("%c", c);
        }
    };
    
    void print_function(char c)
    {
        printf("%c", c);
    }
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        std::for_each(print_me, print_me + sizeof(print_me)/sizeof(print_me[0]), print_functor());
        printf("\n");
    
        std::for_each(print_me, print_me + sizeof(print_me)/sizeof(print_me[0]), print_function);
    
        return 0;
    }
    

    std::for_each 完全是电话。顺便说一句,在PC上,第一个for_每个都有一个不必要的 lea ecx, [ecx] .

        3
  •  7
  •   Doug T.    15 年前

    与函数指针相比,函数对象的一大优点是,您可以更轻松地在函数对象构造时绑定一些参数。

      class multiplyBy
      {
      private:
          int m_whatToMultiplyBy;
      public:
          multiplyBy(int whatToMultiplyBy) : 
              m_whatToMultiplyBy(whatToMultiplyBy)
          {
          }
    
          void operator()(int& i)
          {
              i = m_whatToMultiplyBy * i;
          }
      }
    
    
      ...
    
      // double the array
      for_each(a.begin(), a.end(), multiplyBy(2));
    

    这种参数的“绑定”可以很好地用 boost::bind boost::function

        4
  •  6
  •   Eric Petroelje    15 年前

    我的意见-#1更好,因为它更简单。

        5
  •  1
  •   Nemanja Trifunovic    15 年前

    函子可以是 more easily inlined 因此,当性能重要时,它可能是一个考虑因素。

        6
  •  1
  •   Martin Beckett    15 年前


    而#2函子看起来更像一个函数调用。

    (有时你不得不对C++语法感到失望)