class scoped_thread
{
std::thread t;
public:
explicit scoped_thread( std::thread t_ ) :
t( std::move( t_ ) )
{
if ( !t.joinable() )
throw std::logic_error( "thread is not joinable" );
}
~scoped_thread()
{
t.join();
}
scoped_thread( scoped_thread const& ) = delete;
scoped_thread& operator=( scoped_thread const& ) = delete;
};
问题>我还应该为scoped_thread
类定义什么,以便我可以将其用作成员变量之一,如下所示?
class T
{
...
void printMe() {}
void init()
{
m_thread = scoped_thread(std::thread(&T::printMe, this));
}
private:
scoped_thread m_thread;
};
或者我必须简单地初始化列表中的成员变量?我认为这不是好方法,因为调用函数将使用未初始化的成员变量。
class T
{
public:
T() : m_thread(std::thread(&T::printMe, this)) {}
...
void printMe() {
// potential use some uninitialized member variables
}
void init()
{
}
private:
scoped_thread m_thread;
};