如果你傳遞了一個臨時變量,而不是一個命名的變量;
C++編譯器會將其解析爲函數聲明,而不是類型對象的定義。
例如:
std::thread my_thread(background_task());
這裏相當與聲明瞭一個名爲my_thread的函數,這個函數帶有一個參數(函數指針指向沒有參數並返回background_task對象的函數),返回一個 std::thread 對象的函數,而非啓動了一個線程;
寫成下邊這樣可能更好理解一些:
class background_task
{
public:
background_task operator()()
{
std::cout << "hello concurrency world!" << std::endl;
return *this;
}
void doSomeWork() { std::cout << "hello do some work!" << std::endl; }
};
C++ std::thread my_thread(background_task (*)())
background_task a;
std::thread th(&background_task::doSomeWork, &a);