前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++ stl库bind函数模板用法的注意事项

C++ stl库bind函数模板用法的注意事项

作者头像
学徒漠筱歌
发布2022-07-17 10:30:10
4120
发布2022-07-17 10:30:10
举报
文章被收录于专栏:ZMHZMH

类成员函数

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

代码语言:javascript
复制
#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进行引用传递参数,如:

代码语言:javascript
复制
    auto func3 = bind(&TesSt::update, std::ref(g_test_st), "hihi");

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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-10-01,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 类成员函数
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档