当比较函数和仿函数,它经常被提及的是仿函数在一个函数的一个优点是仿函数是有状态的。状态数据VS全局函数
然而,在这段代码,在我看来,一个功能可能是有状态的了。那么我在做什么/理解错误?
struct Accumulator
{
int counter = 0;
int operator()(int i)
{
counter += i;
return counter;
}
};
int Accumulate(int i)
{
static int counter = 0;
counter += i;
return counter;
};
int main()
{
Accumulator acc;
std::vector<int> vec{1,2,3,4};
Accumulator acc2 = std::for_each(vec.begin(), vec.end(), acc);
int d1 = acc(0); // 0, acc is passed by value
int d2 = acc2(0); // 10
std::for_each(vec.begin(), vec.end(), Accumulate);
int d4 = Accumulate(0); // 10
return 0;
}
你怎么建议你把它重新开始吗? – chris
@chris:你能重新配制吗? – Korchkidu
对于状态使用'static'的函数,状态将在任何/所有用途和调用之间共享。根据使用情况,您可能需要一些“重置”功能。对于仿函数,您可以轻松创建许多独立的函数。 – crashmstr