ref in thread | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

ref in thread

Hi Please refer below code: https://code.sololearn.com/cA17a5A8a10a I was asked to answer why thread object does not take argument without ref. I mean why thread t(incrementVal,x); does not compile. I tried to understand error populated on SL, but could not understand. Can anyone suggest why ref is required unlike normal function call?

15th Apr 2021, 9:00 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
1 Answer
+ 1
That's because arguments of thread function are copied (or moved) by value, so in order to pass a reference to it, you would need to use reference_wrapper ( via std::ref() or std::cref() ) You can also see this in documentation of thread (from cppreference) 👇 https://en.cppreference.com/w/cpp/thread/thread/thread#Notes
15th Apr 2021, 5:09 PM
Arsenic
Arsenic - avatar