1

My code goes like this :-

#include <iostream>
#include <thread>
using namespace std;
void swapno (int &a, int &b)
{
    int temp=a;
    a=b;
    b=temp;
}
int main()
{
    int x=5, y=7;
    cout << "x = " << x << "\ty = " << y << "\n";
    thread t (swapno, x, y);
    t.join();
    cout << "x = " << x << "\ty = " << y << "\n";
    return 0;
}

This code fails to compile. Can anyone help me out why ? Not only this code but the code in this also failed to send std::unique_ptr by reference. What's wrong with std::thread ?

Ankit Acharya
  • 2,833
  • 3
  • 18
  • 29
  • You may be explicit with reference by using `std::ref` (i.e `thread t (swapno, std::ref(x), std::ref(y));`). – Jarod42 Nov 24 '15 at 13:37

2 Answers2

8

The problem is that std::thread copies its arguments and stores them internally. If you want to pass an argument by reference you need to use the std::ref or std::cref functions to create reference wrappers.

Like

thread t (swapno, std::ref(x), std::ref(y));
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

You can do this, instead:

    #include <iostream>
    #include <thread>
    void swapno (int *a, int *b)
    {
        int temp=*a;
        *a=*b;
        *b=temp;
    }
    int main()
    {
        int x = 5, y = 7;
        std::cout << "x = " << x << "\ty = " << y << "\n";
        std::thread t (swapno, &x, &y);
        t.join();
        std::cout << "x = " << x << "\ty = " << y << "\n";
        return 0;
    }

You should achieve the same result ;)

Michael
  • 876
  • 9
  • 29