I would like to pass std::thread temporary object directly to my ThreadGuard class but somehow that is not producing any output, however if I first create local std::thread variable and pass that to constructor then it is working fine. So my question is can't we pass temporary thread to function taking rvalue reference parameter ?
#include <iostream>
#include <thread>
using namespace std;
class ThreadGuard
{
private:
std::thread& m_t;
public:
ThreadGuard(std::thread& t):m_t(t)
{
std::cout<<"By lvalue ref constructor "<<std::endl;
}
ThreadGuard(std::thread&& t):m_t(t)
{
std::cout<<"By rvalue ref constructor "<<std::endl;
}
~ThreadGuard()
{
if(m_t.joinable())
{
m_t.join();
}
}
};
void foo()
{
std::cout<<"Inside foo..."<<std::endl;
}
int main()
{
//This is working
//std::thread th(foo);
//ThreadGuard t1(th);
//This is not giving any output
ThreadGuard t(std::thread(foo));
return 0;
}