In below code I could not understand why move constructor of class is called twice considering that my thread function is taking argument by rvalue reference and so I was hoping move constructor will be called only once when arguments will be moved to thread constructor.Can somebody give insights on how thread constructor works and how it passes argument to thread function.
#include <iostream>
#include <thread>
#include <chrono>
class Test {
public:
Test() {}
Test(Test&&)
{
std::cout<<"Move Constructor Called..."<<std::endl;
}
};
void my_thread_func(Test&& obj)
{
using namespace std::chrono_literals;
std::cout<<"Inside thread function..."<<std::endl;
std::this_thread::sleep_for(2s);
}
int main() {
std::thread t(my_thread_func,Test());
std::cout << "Hello World!\n";
t.join();
return 0;
}
This question is not concerned with that thread constructor arguments are passed by value and it is more concerned with why move constructor is called twice ?
std::cout<<"Move Constructor Called..."<<std::endl;
and when execution stops there, have a look at call stack (from whereTest::Test()
has been called). I suspect one call instd::thread::thread()
and another in call ofmy_thread_func()
. I would enjoy to read what you can observe in debugger. – Obelstd::thread
object that takeTest
by value and we can also see that (at least on gcc) there is astd::shared_ptr
to a_Impl_Base
. How wouldTest
get passed fromstd::thread
to_Impl_Base
without an additional move? – Atmometer