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的引用内容,并不是副本。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有