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::bind1st
和std::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