#include <iostream>
#include <thread>
class MyClass {
public:
MyClass(int val) : val_(val) {}
int val_{0};
};
void threadFunction(MyClass myObj) {
// do something ...
}
int main() {
MyClass obj(42);
std::thread t1(threadFunction, obj);
std::thread t2([=]() {
threadFunction(obj);
});
t1.join();
t2.join();
return 0;
}
In thread t1, I called threadfunction directly whereas in thread t2, I put the call of threadFunction in a lambda.
Are these two ways of thread creation equivalent?
t1copiesobjonce (the function takes it by value) andt2copies it twice (the lambda takes a copy and the function takes it by value again).std::thread::thread, so I think both involve 2 copiesthreadFunctionaccepts by value, I could still capture by reference in the lambda[&]because the copy is made in the lambda. Makes sense?