Как говорит @JesperJuhl, вы передаете копию a
, поэтому переменные main никогда не изменяются, но, кроме того, ссылки не могут быть переданы другим потокам. Параметры потока всегда передаются по значению, поэтому вам нужно передать указатель или reference_wrapper
, который позволяет передавать ссылку, но заключенный в копируемый объект:
#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;
}