[英]`scoped_thread` pass by value of `std::thread`
我已經從中看到以下實現
運行中的c ++並發
scoped_thread
的設計是使它實際上擁有線程的所有權。
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;
};
用法示例:
struct func;
void f()
{
int some_local_state;
scoped_thread t(std::thread(func(some_local_state)));
do_something_in_current_thread();
}
如果調用者改用以下代碼會發生什么?
struct func;
void f()
{
int some_local_state;
std::thread t1(func(some_local_state));
scoped_thread t(t1); // pass by value
do_something_in_current_thread();
}
我擔心的是, pass by value
將導致scoped_thread不擁有線程t1。
有人可以幫我澄清一下嗎?
scoped_thread t(t1); // pass by value
那不會編譯,因為std::thread
是不可復制的(因為它具有move構造函數,但沒有copy構造函數)。
從現有std::thread
構造scoped_thread
的唯一方法是移動它,這會轉移所有權:
scoped_thread t(std::move(t1));
因此,您不必擔心。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.