【发布时间】:2016-07-13 07:23:12
【问题描述】:
我对 std::for_each 和仿函数代理对象有以下问题。 见以下代码:
struct Functor {
std::vector<int> data;
const unsigned mID;
static unsigned id;
Functor() : mID(id++) {
std::cout << "Functor constructed with id: " << mID << std::endl;
}
~Functor() {
std::cout << "Functor dtor: " << mID << std::endl;
}
void operator() (int i) {
std::cout << "Functor print: " << i << std::endl;
data.push_back(i);
std::cout << "Dump: ";
for(int i = 0; i < data.size(); ++i)
std::cout << data[i] << " ";
std::cout << std::endl;
}
};
unsigned Functor::id = 0;
从上面看,代理对象只做两件事,它将数据打印到 CMD 并存储一个副本供自己使用。下面是该对象的示例用例:
int main () {
std::vector<int> intvec;
for(int i = 0; i < 10; ++i)
intvec.push_back(i);
Functor myfunctor;
std::for_each(intvec.begin(), intvec.end(), myfunctor);
std::cout << "Data in my functor: " << myfunctor.data.size() << std::endl;
for(int i = 0; i < myfunctor.data.size(); ++i)
std::cout << "myfunctor data: " << myfunctor.data[i] << std::endl;
return 0;
}
这对我来说真的很可疑。生成的输出是我的函子代理对象被构造了一次但被解构了三次!有东西绕过了构造调用。
同样由于在 std::for_each 结束时调用了析构函数,Functor.data 也是空的!
有没有办法确保 Functor 中的数据保持持久性?我希望在 std::for_each 等函数内部使用时跟踪我的仿函数的状态(基本上任何给定的 std 算法函数都可以接受一元仿函数)
请注意,我只使用 c++03。非常感谢。
【问题讨论】: