function object as parameter of std::thread object

Why use '&' symbol in the code bellow, when thread object called like "std::thread t(&X::do_lengthy_work, &my_x, num);"? In other words, why use object reference for function object as the parameter?

1
2
3
4
5
6
7
8
class X
{
public:
void do_lengthy_work(int);
};
X my_x;
int num(0);
std::thread t(&X::do_lengthy_work, &my_x, num); //what's the use of "&" operator symbol  
Last edited on
& has 3 meanings. it can mean bit-wise and. 2 and 4 is true logically (both are not zero) but are zero bitwise (2 and 0) bit result along with (4 and zero) bit result becomes zero.

it can mean references: int &x = y; //x is a new name for y. change one and the other also changed.

it can mean address of, taking a pointer from an existing item. That is what you are seeing here. int* ip = &x; //ip is a pointer to x. *ip = 3; //changes x.

how to know the difference?! A couple of quick rules of thumb that is almost always true will get this for you most of the time and by the time you see something where the rule fails, you will understand things a lot more. The rule is... if its in an expression (usually boolean or integer bit manipulations) it is bitwise and if (x & y) or while (a & b) or x = z & 0x255 etc. If it its attached to a variable in a declaration, it will be a reference: int &x = //reference or void foo (int &z) //reference etc. If it is on the right side of an assignment or similar, it is a pointer: ip = &x, or foo (&x);//foo must take a pointer as a parameter. Functions are the hardest to read at first: if the & is in the function's header, its a reference, if it is used when it is being called, it is a pointer.

So all that to say, t is being constructed, and constructors are a type of function. So by the above, when calling a function, it is a pointer.

Last edited on
> In other words, why use object reference for function object as the parameter?

&X::do_lengthy_work yields a pointer to the non-static member function.
The first argument to the thread constructor is the CallableObject to be executed by the new thread.

Topic archived. No new replies allowed.