这两种方法中的哪一种更好,为什么?
方法1:
void fun(int i) {
//do stuff
}
...
for_each(a.begin(), a.end(), fun);
Run Code Online (Sandbox Code Playgroud)
方法2:
class functor {
public:
void operator()(int i);
};
...
for_each(a.begin(), a.end(), functor());
Run Code Online (Sandbox Code Playgroud)
编辑:应该用这种方式制定,在什么情况下上述方法之一优于另一种?
非常感谢!
Kon*_*lph 19
函数可能(并且将会)被简单地内联 - 这不是针对常规函数指针.
因此,仿函数具有真正的性能优势,在紧密循环中可能是巨大的.此外,仿函数通常更容易组合,特别是使用STL更好:std::bindx不会对函数指针起作用.
我讨厌他们如何混乱代码但是给了所有的优点,我更喜欢它们而不是函数指针.
MSN*_*MSN 11
为了清除对编译器可以内联的误解,一个足够好的编译器可以内联函数指针.它可以更容易地内联函数对象,因为有更多的静态信息可用.例如,指向不带参数并返回bool的函数的指针是bool(*)()类型,而仿函数有一个显式类型,即仿函数,模板实例化可以静态调用仿函数运算符,而不是而不必通过函数指针调用.
但实际上,主要是为编译器提供足够的信息来有效地进行优化.
例如,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;
}
Run Code Online (Sandbox Code Playgroud)
std::for_each完全内联两个电话.顺便说一句,在PC上,第一个for_each没有必要lea ecx, [ecx].
函数对象相对于函数指针的一大优点是,您可以更容易地在函数对象构造中绑定一些参数.
可能会这样做的仿函数的一个例子
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));
Run Code Online (Sandbox Code Playgroud)
如果你可以使用boost,那么使用boost :: bind和boost :: function可以很好地完成参数的这种"绑定" .