类成员函数

bind可以包装类成员函数,创建函数对象。其中有接收类类型和类指针类型的版本,如:

#include <iostream>#include <memory>#include <functional>using namespace std;struct TesSt { TesSt() {} void update(const string &in_str) { str = in_str; cout << "str:" << str << endl;; } string str;};TesSt g_test_st;int main () { auto func1 = bind(&TesSt::update, &g_test_st, "hihi"); auto func2 = bind(TesSt::update, &g_test_st, "hihi"); auto func3 = bind(&TesSt::update, g_test_st, "hihi"); auto func4 = bind(TesSt::update, g_test_st, "hihi"); return 0;}

如果不做任何处理的话,bind函数是通过值拷贝的方式进行参数传递。也就是说,func1、func2是经过被拷贝的类指针构造,调用会更新g_test_st内容;func3、func4是值拷贝构造,调用时更新的是g_test_st的副本,不会影响原来的类变量。

另外,可以通过std::ref,使bind进行引用传递参数,如:

auto func3 = bind(&TesSt::update, std::ref(g_test_st), "hihi");

这样func3调用时更新的是g_test_st的引用内容,并不是副本。