为什么我的仿函数成员变量 "reset" ? (c++)

why does my functor member variable "reset" ? (c++)

我正在学习如何使用仿函数,所以我创建了一个,但我不明白为什么我的计数器变量在程序结束时为 0。

这里是代码:

#include"stdafx.h"
#include<iostream>
#include<vector>
#include<algorithm>
#include<map>
#include<list>


using namespace std;

class myFunctor {
public:
    myFunctor():counter(0) {}
    void operator()(int i) { cout << "in the functor: " << i ; counter++; cout << "   counter=" << counter << endl; }
    int getCounter() const { return counter; }
private:
    int counter;
};

int main()
{
    vector<int> v{ 1,2,3,4,5,6,7,8,9,10 };
    myFunctor f;

    for_each(v.begin(), v.end(), f);

    cout << "counter=" << f.getCounter() << endl;

    return 0;
}

结果如下:

in the functor: 1   counter=1
in the functor: 2   counter=2
in the functor: 3   counter=3
in the functor: 4   counter=4
in the functor: 5   counter=5
in the functor: 6   counter=6
in the functor: 7   counter=7
in the functor: 8   counter=8
in the functor: 9   counter=9
in the functor: 10   counter=10
counter=0

如果您查看 for_each 的签名,您会发现它按值接受仿函数,因此当算法终止时,您在 for_each 中看到的更改不会反映在外部。

http://en.cppreference.com/w/cpp/algorithm/for_each

template< class InputIt, class UnaryFunction >
UnaryFunction for_each( InputIt first, InputIt last, UnaryFunction f );

如果你想完成这项工作,你将不得不使用 std::ref 生成一个引用包装器并按值传递它。

std::for_each(vec.begin(), vec.end(), std::ref(functor));

看看 documentation for std::ref and reference_wrapper to see how and why this works (the key point is that std::reference_wrapper has an operator() to work with functors http://en.cppreference.com/w/cpp/utility/functional/reference_wrapper/operator())。

查看每个的签名:

http://en.cppreference.com/w/cpp/algorithm/for_each

它复制了仿函数 f,所以原件没有被修改。

虽然 Curious 的答案是最好的解决方案,但这里是另一个:

class myFunctor {
public:
    myFunctor():counter(std::make_shared<int>(0)) {}
    void operator()(int i) { cout << "in the functor: " << i ; ++*counter; cout << "   counter=" << *counter << endl; }
    int getCounter() const { return *counter; }
private:
    std::shared_ptr<int> counter;
};