I'm trying to use lambdas with threads in c++, and use captures as a way of passing data to the thread. The following code prints "ConnectionInfo(copy)" three times when the thread is created. Is there anyway to reduce it to a single copy? I'm not sure why it's copied the extra two times.
#include <iostream>
#include <functional>
#include <memory>
#include <thread>
using namespace std;
class ConnectionInfo
{
public:
ConnectionInfo():port(0) {}
ConnectionInfo(int p):port(p) {}
ConnectionInfo(const ConnectionInfo &other)
{
std::cout << "ConnectionInfo(copy)" << std::endl;
port = other.port;
}
int port;
void Connect() {};
};
int main() {
std::cout << "Create" << std::endl;
ConnectionInfo c(2);
std::cout << "Thread" << std::endl;
std::thread t(
[a = c]() mutable
{
a.Connect();
std::cout << "Done" << std::endl;
}
);
std::cout << "Joining" << std::endl;
t.join();
std::cout << "Joined" << std::endl;
return 0;
}
Output is:
Create
Thread
ConnectionInfo(copy)
ConnectionInfo(copy)
ConnectionInfo(copy)
Joining
Done
Joined