类成员函数
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 的引用内容, 并不是副本.
来源: http://www.bubuko.com/infodetail-2788997.html