Why move constructor is called twice when passing

2020-06-23 06:05发布

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 ?

1条回答
该账号已被封号
2楼-- · 2020-06-23 06:34

The extra move construction is allowed by the standard, but is potentially less efficient. That missed-optimization bug was https://gcc.gnu.org/PR69724 and has been fixed for the upcoming GCC 10 release.

查看更多
登录 后发表回答