In writing test code for this question I found that the commented line below does not compile on GCC 4.7.2:
#include <thread>
#include <iostream>
struct S {
void f() {
std::cout << "Calling f()" << std::endl;
}
};
int main()
{
S s;
// std::thread t(&S::f, s); // does not compile?
std::thread t(&S::f, &s);
t.join();
}
But cppreference seems to claim that the "this" argument can be passed equivalently as an object, reference to object, or pointer to object:
If f is pointer to a member function of class T, then it is called. The return value is ignored. Effectively, the following code is executed: (t1.*f)(t2, ..., tN) if the type of t1 is either T, reference to T or reference to type derived from T. ((*t1).*f)(t2, ..., tN) otherwise.
I actually think this sounds terrible, and would prefer std::thread
only allow either pointer or reference semantics instead of accepting them interchangeably, but given that it seems like it's supposed to, is the above a GCC/libstdc++ bug (or am I misinterpreting cppreference)?
` it needs to dereference the ptr-like thing. Supporting both those uses cases is important, so that the new thread (or call wrapper, or other type defined in terms of _INVOKE_) can take ownership of its arguments, so they don't go out of scope before they are needed.– Jonathan Wakely Mar 02 '13 at 01:35