Reputation: 21
void ThreadFn(int& i)
{
cout<<"Hi from thread "<<i<<endl;
}
int x = 0;
void CreateThreads(vector<thread>& workers)
{
for(int i = 0; i< 10; i++)
{
workers.push_back(thread(&ThreadFn, x));
}
}
I was expecting a compilation error in the thread creation (workers.push_back(thread(&ThreadFn, x));
) since x
should be passed by ref.
I though the right syntax should've been:
workers.push_back(thread(&ThreadFn, std::ref(x)));
Of course, the code compiles fine and also behaves properly. I am using VC11
. Any idea why this isn't being flagged?
Upvotes: 2
Views: 192
Reputation: 171403
This is a VC11 bug, the thread
object makes internal copies of the arguments (as it should) but then it doesn't forward them to the ThreadFn
function correctly, so what happens is the reference binds to the thread
object's internal int
member.
GCC's std::thread
used to have a similar bug because we used std::bind
to implement it, but I replaced the use of std::bind
with a different implementation detail that forwards the captured arguments to the function by value.
Upvotes: 3