[英]Can someone explain the following strange function declarations?
std::thread f()
{
void some_function(); // <- here
return std::thread(some_function);
}
std::thread g()
{
void some_other_function(int); // <- here
std::thread t(some_other_function,42);
return t;
}
像這樣的行:
void some_function();
只需聲明一個函數,該函數將在以后定義。 函數不一定必須在函數范圍之外聲明。
正如您所想,這只是一個函數聲明。 通常(推薦)將函數聲明放在頭文件中,但這絕不是必需的。 它們可能在功能體內。
定義一個返回thread
對象的函數:
std::thread f()
{
聲明一個extern
不帶參數的返回功能void
(通常這不是在局部范圍內進行的,但它是有效的):
void some_function();
啟動執行該功能的線程,並返回一個句柄:
return std::thread(some_function);
}
與之前相同:
std::thread g()
{
void some_other_function(int);
但這是無效的。 您無法復制線程,因此從技術上講,創建本地thread
對象然后返回它是不可行的。 如果對此進行編譯,我會感到驚訝,但是如果編譯的話,在為調試器進行構建時可能會中斷。
std::thread t(some_other_function,42);
return t;
}
但是,這將起作用:
return std::move( t );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.