原来
bool Myclass::connect() {
std::function<void()>f = std::bind(&Myclass::loopCheckStatus, this);
new std::thread(f);
return true;
}
void Myclass::loopCheckStatus() {
while (true) {
//check something
}
}
改造后
bool Myclass::connect() {
// Using a lambda expression to call loopCheckStatus
auto f = [*this]() { loopCheckStatus(); };
std::thread t(f);
return true;
}
注意这里的*this,这么写的原因是因为相当于通过lambda表达式通过拷贝来捕获this指针,防止lambda对无效数据进行操作。参考:1.https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#f53-avoid-capturing-by-reference-in-lambdas-that-will-be-used-non-locally-including-returned-stored-on-the-heap-or-passed-to-another-thread
2.https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#f54-when-writing-a-lambda-that-captures-this-or-any-class-data-member-dont-use--default-capture
更推荐的写法
std::thread thread(&mysql::do_flush_torrents, this);
因为传给thread构造函数的可调用对象的参数,默认是按值拷贝传递的,这样this指针就是拷贝了一份
GitHubID:shiyi23
践行 活在当下 的理念