As @JesperJuhl says, you are passing a copy of a
so the main's variables is never modified, but, besides, references cannot be passed to other threads. The thread's parameters are always passed by value, so, you need to pass a pointer or a reference_wrapper
, which allows to pass a reference, but wrapped in a copyable object:
#include <iostream>
#include <thread>
using namespace std;
struct A{
void Add(){
++val;
}
int val = 0;
};
int main(){
A a;
// Passing a reference_wrapper is the standard way.
// Passing a pointer would imply to change your method signature
// and implementation if it were a free function instead of a
// class member function.
// In your specific case it is irrelevant though.
thread t(&A::Add,std::ref(a));
// or thread t(&A::Add,&a);
t.join();
std::cout << a.val << std::endl;
}