1

I use Reference(&) here,but the a didn't change.Why? While i use Pointer(*) the value have changed.

int all=0; 
void call_from_thread(int & a)  
{
   a = 5;
}

int main() 
{
    thread s = thread(call_from_thread, all);
    s.join();
    return 0;
}

Another program,in this case, i also use Reference(&),but the value have changed. Why the value a in thread didn't change?

void Func3(int &x)
{
    x = x + 10;
}

int main() {

    int n = 0;
    Func3(n);
    cout << “n = ” << n << endl; // n = 10
}
1

1 Answer 1

7

The std::thread constructor makes copies of its parameters during the thread creation step.... ordinary references don't survive the trip, and the call_from_thread function receives a reference to the copy.

Details can be found in the Standard. The thread::thread constructor behavior is described as

Constructs an object of type thread. The new thread of execution executes INVOKE(DECAY_COPY(std::forward<F>(f)), DECAY_COPY(std::forward<Args>(args))...) with the calls to DECAY_COPY being evaluated in the constructing thread.

The exact definition of DECAY_COPY is quite complex, but as the name suggests, it ignores references and makes a value copy.

A simple workaround is to use std::ref.

thread s = thread(call_from_thread, std::ref(all));

This keeps a pointer through the copies, and only resolves to the actual target when the reference parameter is bound.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.