std::bind()和this相遇

eg1:

void EventTrigger::Run()
{
RegisterDetector();
if (ParseMap(AppContext::GetResourceFile("global_map.path")) == false) {
DLOG(ERROR) << "parse map failed";
}
m_run_flag = true;
m_detect_thread = std::thread(&EventTrigger::DetectThread, this);
}

eg2:

void TaskManager::StartTaskThread()
{
//PullTaskStatus2Web("无任务");
//Agent::GetAppClient()
m_is_running = false;
if (m_task_thread.joinable()) {
m_task_thread.join();
}
//创建任务线程
m_is_running = true;
m_task_thread = std::thread(std::bind(&TaskManager::TaskThread, this));
}

代码中经常遇到std::bind 绑定this的情况,什么时候需要this,这个this在这儿有什么用呢?

首先看c11里std::bind的作用

C++11中提供了std::bind。bind()函数的意义就像它的函数名一样,是用来绑定函数调用的某些参数的。

bind的思想实际上是一种延迟计算的思想,将可调用对象保存起来,然后在需要的时候再调用。而且这种绑定是非常灵活的,不论是普通函数、函数对象、还是成员函数都可以绑定,而且其参数可以支持占位符,比如你可以这样绑定一个二元函数auto f = bind(&func, _1, _2);,调用的时候通过f(1,2)实现调用。

简单的认为就是std::bind就是std::bind1ststd::bind2nd的加强版。

 

#include <iostream>
#include <functional>
using namespace std;

int TestFunc(int a, char c, float f)
{
cout << a << endl;
cout << c << endl;
cout << f << endl;

return a;
}

int main()
{
auto bindFunc1 = bind(TestFunc, std::placeholders::_1, 'A', 100.1);
bindFunc1(10);

cout << "=================================\n";
//把TestFunc绑定到bindFunc2上,bindFunc2的第二个参数为TestFunc的第一个参数
//bindFunc2的第一个参数为TestFunc的第二个参数,最后一个参数固定为100.1
//类似于 TestFunc(bindFunc2's_var_2, bindFunc2's_var_1, 100.1);
auto bindFunc2 = bind(TestFunc, std::placeholders::_2, std::placeholders::_1, 100.1);
bindFunc2('B', 10);

cout << "=================================\n";

auto bindFunc3 = bind(TestFunc, std::placeholders::_2, std::placeholders::_3, std::placeholders::_1);
bindFunc3(100.1, 30, 'C');

return 0;
}

从上面的代码可以看到,bind能够在绑定时候就同时绑定一部分参数,未提供的参数则使用占位符表示,然后在运行时传入实际的参数值。PS:绑定的参数将会以值传递的方式传递给具体函数,占位符将会以引用传递。众所周知,静态成员函数其实可以看做是全局函数,而非静态成员函数则需要传递this指针作为第一个参数,所以std::bind能很容易地绑定成员函数。

 

参考链接:

https://blog.csdn.net/u013654125/article/details/100140328

https://blog.csdn.net/lqw198421/article/details/115087355

 

原文链接: https://www.cnblogs.com/yunyuanfeng/p/15032506.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    std::bind()和this相遇

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/212372

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月13日 上午1:14
下一篇 2023年2月13日 上午1:14

相关推荐