Reputation: 344
I'm trying to understand how std::thread
is used.
The header looks as follows:
template< class Function, class... Args >
explicit thread( Function&& f, Args&&... args );
f
is a universal ref or rvalue? From what I found online:"If T is getting deduced and variable / parameter type is unqualified T&& , then only it’s a Universal Reference."
what does unqualified T&&
refer to? auto
or template
?
If I have a function foo
, I could call use it like std::thread(foo)
. Does that mean foo
is being used as an lvalue reference because it doesn't qualify for rvalue reference?
Why does the way a function is passed differ from in the case of member functions? if foo
was a part of the class, you won't be able to use it like std::thread(obj.foo)
- instead std::thread(&Class::foo, &obj)
works. What's the logical reasoning behind it?
How does one pass a local variable/vector to a thread? I tried the following but in the function itself, I can't access any vector elements even though vector.size()
does output correctly.
void Class::foo(vector<int>v)
{
std::cout<<v[0]; // prints nothing
}
int main(void)
{
std::vector<int>v = {12,3};
Class obj;
std::thread t1(&Class::foo, &obj, v);
t1.join();
}
Upvotes: 1
Views: 98
Reputation: 238401
what does unqualified
T&&
refer to?
It refers to the function parameter of the function template. f
and args...
are the parameters. They satifsy the described requirment of being forwarding references (as long as the template type argument isn't passed explicitly inn which case the type would not be deduced from the function argument).
Why does the way a function is passed differ from in the case of member functions?
Because non static member functions have an implicit instance parameter, and because they don't implicitly decay to pointer to member function.
How does one pass a local variable/vector to a thread?
Depends on context. Copying is usually simplest.
Upvotes: 1