使用绑定与成员函数

using bind with member function

本文关键字:成员 函数 绑定      更新时间:2023-10-16

为什么两个bind版本都可以毫无问题地编译和工作,即使我在每次调用中使用不同的参数类型?

  1. 版本 1 -> 参数 foo 与
  2. 版本 2 -> foo 的参数地址

我预计版本 1 会产生编译错误......


#include <iostream>
#include <functional>
using namespace std;
class Test   
{   
public:
   bool doSomething(){ std::cout << "xxx"; return true;};   
};
int main() {
Test foo;
// Version 1 using foo
std::function<bool(void)> testFct = std::bind(&Test::doSomething, foo);
// Version 2 using &foo
std::function<bool(void)> testFct2 = std::bind(&Test::doSomething, &foo);
testFct();
testFct2();
return 0;
}
std::function<bool(void)> testFct = std::bind(&Test::doSomething, foo);

这将绑定到 foo 的副本,并调用该函数作为copy.doSomething()。请注意,如果您期望foo本身调用函数,这将是错误的。

std::function<bool(void)> testFct2 = std::bind(&Test::doSomething, &foo);

这将绑定到指向foo指针,并以pointer->doSomething()调用该函数。请注意,如果在调用函数之前foo已被销毁,这将是错误的。

我预计版本 1 会产生编译错误......

如果需要,您可以通过使Test不可复制来禁止此行为。