gpt4 book ai didi

c++ - 函数对象与状态

转载 作者:行者123 更新时间:2023-11-27 22:53:40 24 4
gpt4 key购买 nike

我已经使用函数对象来了解传递的对象发生了什么,以及它如何影响对象的状态。这是测试代码的片段:

#include <iostream>
//#include <boost/function.hpp>
//using boost::function;

#include <functional>
using std::function;
using std::bind;

struct A {
A() { std::cout << "Creating..." << "\n"; }
void operator()() { call(); }
void call() { std::cout << "Executing call..." << "\n"; }
virtual ~A() { std::cout << "Destroying" << "\n"; }
};

typedef function<void ()> Func;

struct B{
Func f;
B(Func ff) : f(ff) {}
void call() {f();}
};

int main(int argc, char *argv[])
{
{
A a;
B b(a);
for (int i = 0; i < 5; ++i)
b.call();
}
{
A a2;
B b2(bind(&A::call, &a2));
for (int i = 0; i < 5; ++i)
b2.call();
}
return 0;
}

/** Output **
Creating...
Destroying
Destroying
Executing call...
Executing call...
Executing call...
Executing call...
Executing call...
Destroying
Destroying
Creating...
Executing call...
Executing call...
Executing call...
Executing call...
Executing call...
Destroying
*/

当我传递重载了 operator() 的对象时,有一些对析构函数的多次调用;并且没有创建任何对象!所以,我不能依赖,也就是说,对象状态的保真度。这是否意味着当我为回调传递一个函数对象(带有重载的 operator())时,我应该假设对象的状态没有被保留? 这是预期的行为吗?

另一方面,从另一种类型的对象内部回调绑定(bind)成员函数会产生非常稳定的行为(我不知道该用什么术语);也就是说,我希望保留对象状态;确实如此! 这也是有意为之的行为吗? IOW,这就是仿函数的普遍理解方式吗?

附言:

我还使用 boost::function 和 boost::bind 对其进行了检查 --- 结果非常相似。可能需要另一个线程来讨论细微差别。

最佳答案

关于“无构造函数”:存在对拷贝构造函数的调用。

尝试更多检测:

struct A {
A() { std::cout << "Creating..." << "\n"; }
void operator()() { call(); }
A(const A&) { std::cout << "Copying" << "\n"; }
A(A&&) { std::cout << "Moving" << "\n"; } // Assuming C++11
void call() { std::cout << "Executing call..." << "\n"; }
virtual ~A() { std::cout << "Destroying" << "\n"; }
};

关于复制:

  • 您将按值调用的对象移交给 B 的构造函数。它必须被复制。
  • 绑定(bind),如果您提交一个值,这就是预期的行为。您要绑定(bind)的可调用对象可能是临时的。因此,默认行为是复制。

如果您知道您的可调用对象将存活足够长的时间(正如您的代码中的情况),您可以通过使用引用包装器来避免这种情况。尝试:

int main(int argc, char *argv[])
{
{
A a;
{
B b(a);
}
std::cout << "-------------\n";
B(std::ref(a));
std::cout << "-------------\n";
B(bind(&A::call, a));
std::cout << "-------------\n";
B(bind(&A::call, &a));
std::cout << "-------------\n";
B(bind(&A::call, std::ref(a)));
std::cout << "-------------\n";
}
std::cout << "-------------\n";
return 0;
}

关于c++ - 函数对象与状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35169864/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com