Why move constructor is called twice when passing temporaries to thread function?

元气小坏坏 提交于 2020-01-12 09:18:26

问题


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 ?

来源:https://stackoverflow.com/questions/50362849/why-move-constructor-is-called-twice-when-passing-temporaries-to-thread-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!